from yattag import Doc, indent


class XMLGenerator:
    """
    Генератор XML синхронизации в формате, совместимом с test1_full/srv_interp.py
    """

    def generate(self, sync_data: dict, path: str, hw):
        number_of_blocks = sync_data["number_of_blocks"]
        gate_rf = sync_data["gate_rf"]
        gate_tr_switch = sync_data["gate_tr_switch"]
        gate_adc = sync_data["gate_adc"]
        blocks_duration = sync_data["blocks_duration"]
        synchro_block_timer = sync_data["synchro_block_timer"]
        min_block_time = sync_data["min_block_time"]

        doc, tag, text = Doc().tagtext()

        with tag("root"):
            with tag("ParamCount"):
                text(number_of_blocks + 1)

            adc_times_values = []
            adc_times_starts = []

            with tag("RF"):
                with tag("RF1"):
                    text(0)
                for rf_iter in range(number_of_blocks):
                    with tag("RF" + str(rf_iter + 2)):
                        text(gate_rf[rf_iter])

            with tag("SW"):
                with tag("SW1"):
                    text(1)
                for sw_iter in range(number_of_blocks):
                    with tag("SW" + str(sw_iter + 2)):
                        text(gate_tr_switch[sw_iter])

            with tag("ADC"):
                with tag("ADC1"):
                    text(0)
                for adc_iter in range(number_of_blocks):
                    if gate_adc[adc_iter] == 1:
                        adc_times_values.append(blocks_duration[adc_iter])
                        adc_times_starts.append(sum(blocks_duration[0:adc_iter]))
                    with tag("ADC" + str(adc_iter + 2)):
                        text(gate_adc[adc_iter])

            with tag("GR"):
                with tag("GR1"):
                    text(1)
                for gr_iter in range(number_of_blocks):
                    with tag("GR" + str(gr_iter + 2)):
                        text(0)

            with tag("CL"):
                with tag("CL1"):
                    text(int(min_block_time / synchro_block_timer))
                for cl_iter in range(number_of_blocks):
                    with tag("CL" + str(cl_iter + 2)):
                        text(int(blocks_duration[cl_iter] / synchro_block_timer))

        xml_string = indent(doc.getvalue(), indentation=" " * 4, newline="\r")
        with open(path, "w", encoding="utf-8") as f:
            f.write(xml_string)

        return adc_times_values, adc_times_starts
