"""Writer for ACDTool/RFPostProcess input files."""
import smtk

class RFPostWriter:
    """Writer for ACDTool/RFPostProcess input files.

    The format is mostly regular, so we don't need alot of new code.
    """
    def __init__(self):
        self.scope = None


    def write(self, scope):
        """Entry point for writing rfpost file."""
        self.scope = scope

        # Find RFPostProcess
        rfpost_att = self.scope.sim_atts.findAttribute('RfPostprocess')
        if rfpost_att is None:
            msg = "Internal Error: did not find RfPostprocess attribute"
            self.scope.logger.addError(msg)
            raise RuntimeError(msg)

        # Traverse children, which are all group items
        for i in range(rfpost_att.numberOfItems()):
            item = rfpost_att.item(i)
            if item.isEnabled():
                self._write_section(item)


    def _write_coaxport(self, group_item):
        """Special logic for coaxPort section."""
        for i in range(group_item.numberOfItemsPerGroup()):
            item = group_item.item(0, i)
            if item.name() != 'port-info':
                self._write_rf_item(item)
                continue

            # Special logic for port-info
            num_ports = item.numberOfGroups()
            names = ['portID', 'porta', 'portb']
            for i, name in enumerate(names):
                value_list = [None] * num_ports
                for p in range(num_ports):
                    value_list[p] = item.find(p, name).value()
                value_string = ', '.join(map(str, value_list))
                line = '  {:16s} = {{ {} }}\n'.format(name, value_string)
                self.scope.output.write(line)


    def _write_rf_item(self, item):
        """"""
        if not item.isEnabled():
            return
        line = '  {:16s} = {}\n'.format(item.name(), item.value())
        self.scope.output.write(line)


    def _write_section(self, group_item):
        """"""
        # print('item', item.name())
        self.scope.output.write(group_item.name())
        self.scope.output.write('\n{\n')
        if group_item.name() != 'RFField':
            self.scope.output.write('  ionoff           = 1\n')
        if group_item.name() == 'coaxPort':
            self._write_coaxport(group_item)
        else:
            num_items = group_item.numberOfItemsPerGroup()
            for i in range(num_items):
                item = group_item.item(0, i)
                self._write_rf_item(item)
        self.scope.output.write('}\n')
