import csv
import xml.etree.ElementTree as ET

from gcstruct.gchr import GCHR


def convert_to_row(node: list[ET.Element]) -> list[str]:
    return [child.text for child in node]


def convert_xml_to_csv(xmlfile: str, csvfile: str) -> bool:
    with open(xmlfile) as frh:
        record_list = ET.parse(frh).getroot().find("RecordList")
    header = [child.tag for child in record_list.find("Record")]
    bookings = [GCHR.convert_to_row(node) for node in record_list.findall("Record")]
    with open(csvfile, "w") as fwh:
        cwh = csv.writer(fwh, delimiter=";")
        cwh.writerow(header)
        cwh.writerows(bookings)
    return True


def convert_csv_to_xml(self, csvfile: str, xmlfile: str) -> None:
    self.makes = {"01": "1844"}
    self.sites = {"01-01": "1844"}
    with open(csvfile, "r", encoding="latin-1") as frh:
        csv_reader = csv.DictReader(frh, delimiter=";")
        GCHR.export_skr51_xml(csv_reader, self.bookkeep_filter(), 1, list(self.sites.values())[0], xmlfile)