import os

from lxml import etree, builder
from openpyxl import load_workbook

from .. import classes


def create_mapping(excel_path: str, folder_path: str, project:classes.Project) -> None:
    def create_xml(name: str, object: classes.Object):
        xsd = "http://www.w3.org/2001/XMLSchema"
        xsi = "http://www.w3.org/2001/XMLSchema-instance"

        def create_key_rule() -> None:
            xml_key_rule = etree.SubElement(xml_manipulation_rule, "KeyRule", )
            xml_key_rule.set(f"{{{xsi}}}type", "CompareRule")
            xml_key = etree.SubElement(xml_key_rule, "Key", )
            xml_key.text = "Querprofile-Horizontname"
            xml_value = etree.SubElement(xml_key_rule, "Value", )
            xml_value.text = name
            xml_value.set(f"{{{xsi}}}type", "xsd:string")
            xml_value = etree.SubElement(xml_key_rule, "Compare", )
            xml_value.text = "Equal"

        def create_manipulations() -> None:
            xml_manipulations = etree.SubElement(xml_manipulation_rule, "Manipulations")
            for property_set in object.property_sets:
                for attribut in property_set.attributes:
                    xml_manipulation_base = etree.SubElement(xml_manipulations, "ManipulationBase")
                    xml_manipulation_base.set(f"{{{xsi}}}type", "AddManipulation")
                    xml_key = etree.SubElement(xml_manipulation_base, "Key", )
                    xml_key.text = attribut.name
                    xml_value = etree.SubElement(xml_manipulation_base, "Value", )
                    if attribut == object.ident_attrib:
                        xml_value.text = attribut.value[0]
                    else:
                        xml_value.text = ""
                    xml_value.set(f"{{{xsi}}}type", attribut.data_type.replace("xs:", "xsd:"))

        E = builder.ElementMaker(nsmap={"xsd": xsd, "xsi": xsi})
        xml_role = E.Role()
        xml_name = etree.SubElement(xml_role, "Name")
        xml_name.text = name
        xml_rules = etree.SubElement(xml_role, "Rules")
        xml_manipulation_rule = etree.SubElement(xml_rules, "ManipulationRule")
        xml_description = etree.SubElement(xml_manipulation_rule, "Description")
        xml_description.text = "Autogenerated"
        create_key_rule()
        create_manipulations()

        tree = etree.ElementTree(xml_role)
        tree.write(os.path.join(folder_path, f"{name.replace('/', '_')}.amrx"), pretty_print=True, encoding="utf-8",
                   xml_declaration=True)

    wb = load_workbook(excel_path)
    sheet = wb.active
    if not os.path.isdir(folder_path):
        os.mkdir(folder_path)

    important_rows = [row for i, row in enumerate(sheet.rows) if row[2].value is not None and i != 0]
    object_dict = {obj.ident_attrib.value[0]: obj for obj in project.objects if not obj.is_concept}

    for row in important_rows:
        values = list(map(lambda x: x.value, row))
        if len(values)!= 4:
            raise ValueError("Spaltenkonfiguration nicht korrekt!")
        hz_nummer, hz_name, bauteilName,bauteilklass =values
        create_xml(hz_name, object_dict[bauteilklass])
