import xml.etree.ElementTree as ET
from datetime import datetime
ET.register_namespace('', "http://www.w3.org/2000/09/xmldsig#")


xml_template3 = """
<HDon>
    <DLHDon>
        <TTChung>
        <PBan>None</PBan>
        <THDon>None</THDon>
        <KHMSHDon>None</KHMSHDon>
        <KHHDon>None</KHHDon>
        <SHDon>None</SHDon>
        <NLap>None</NLap>
        <DVTTe>None</DVTTe>
        <TGia>None</TGia>
        <HTTToan>None</HTTToan>
        <MSTTCGP>None</MSTTCGP>
        </TTChung>
        <NDHDon>
            <NBan>
                <Ten>None</Ten>
                <MST>None</MST>
                <DChi>None</DChi>
                <SDThoai>None</SDThoai>
            </NBan>
            <NMua>
                <Ten>None</Ten>
                <MST>None</MST>
                <DChi>None</DChi>
                <SDThoai>None</SDThoai>
                <HVTNMHang>None</HVTNMHang>
            </NMua>
            <DSHHDVu>
                <HHDVu>
                <TChat>None</TChat>
                <STT>None</STT>
                <THHDVu>None</THHDVu>
                <DVTinh>None</DVTinh>
                <SLuong>None</SLuong>
                <DGia>None</DGia>
                <TLCKhau>None</TLCKhau>
                <STCKhau>None</STCKhau>
                <ThTien>None</ThTien>
                <TSuat>None</TSuat>
                </HHDVu>
            </DSHHDVu>
            <TToan>
                <THTTLTSuat>
                <LTSuat>
                    <TSuat>None</TSuat>
                    <ThTien>None</ThTien>
                    <TThue>None</TThue>
                </LTSuat>
                </THTTLTSuat>
                <TgTCThue>None</TgTCThue>
                <TgTThue>None</TgTThue>
                <TTCKTMai>None</TTCKTMai>
                <TgTTTBSo>None</TgTTTBSo>
                <TgTTTBChu>None</TgTTTBChu>
            </TToan>
        </NDHDon>
    </DLHDon>
    <MCCQT Id="None">None</MCCQT>
    <DLQRCode>None</DLQRCode>
</HDon>
"""

def replace_xml_values(xml_str, replacement_dict):
    """ replace xml values

    Args:
        xml_str (_type_): _description_
        replacement_dict (_type_): _description_

    Returns:
        _type_: _description_
    """
    try:
        root = ET.fromstring(xml_str)
        for key, value in replacement_dict.items():
            if not value:
                continue
            if key == "TToan":
                ttoan_element = root.find(".//TToan")
                tsuat_element = ttoan_element.find(".//TgTThue")
                tthue_element = ttoan_element.find(".//TgTTTBSo")
                tthuebchu_element = ttoan_element.find(".//TgTTTBChu")
                if value["TgTThue"]:
                    tsuat_element.text = value["TgTThue"]
                if value["TgTTTBSo"]:
                    tthue_element.text = value["TgTTTBSo"]
                if value["TgTTTBChu"]:
                    tthuebchu_element.text = value["TgTTTBChu"]
            elif key == "NMua":
                nmua_element = root.find(".//NMua")
                for key_ in ["DChi", "SDThoai", "MST", "Ten", "HVTNMHang"]:
                    if value.get(key_, None):
                        nmua_element_key = nmua_element.find(f".//{key_}")
                        nmua_element_key.text = value[key_]
            elif key == "NBan":
                nban_element = root.find(".//NBan")
                for key_ in ["DChi", "SDThoai", "MST", "Ten"]:
                    if value.get(key_, None):
                        nban_element_key = nban_element.find(f".//{key_}")
                        nban_element_key.text = value[key_]
            elif key == "HHDVu":
                dshhdvu_element = root.find(".//DSHHDVu")
                hhdvu_template = root.find(".//HHDVu")
                if hhdvu_template is not None and dshhdvu_element is not None:
                    dshhdvu_element.remove(hhdvu_template)  # Remove the template
                    for hhdvu_data in value:
                        hhdvu_element = ET.SubElement(dshhdvu_element, "HHDVu")
                        for h_key, h_value in hhdvu_data.items():
                            h_element = ET.SubElement(hhdvu_element, h_key)
                            h_element.text = h_value if h_value is not None else "None"
            elif key == "NLap":
                nlap_element = root.find(".//NLap")
                if nlap_element is not None:
                    # Convert the date to yyyy-mm-dd format
                    try:
                        date_obj = datetime.strptime(value, "%d/%m/%Y")
                        formatted_date = date_obj.strftime("%Y-%m-%d")
                        nlap_element.text = formatted_date
                    except ValueError:
                        print(f"Invalid date format for {key}: {value}")
                        nlap_element.text = value
            else:
                element = root.find(f".//{key}")
                if element is not None:
                    element.text = value
        ET.register_namespace("", "http://www.w3.org/2000/09/xmldsig#")
        return ET.tostring(root, encoding="unicode")
    except ET.ParseError as e:
        print(f"Error parsing XML: {e}")
        return None
    
    
def convert_key_names(original_dict):
    """_summary_

    Args:
        original_dict (_type_): _description_

    Returns:
        _type_: _description_
    """
    key_mapping = {
        "table": "HHDVu",
        "Mặt hàng": "THHDVu",
        "Đơn vị tính": "DVTinh",
        "Số lượng": "SLuong",
        "Đơn giá": "DGia",
        "Doanh số mua chưa có thuế": "ThTien",
        "buyer_address_value": "NMua.DChi",
        'buyer_company_name_value': 'NMua.Ten',
        'buyer_personal_name_value': 'NMua.HVTNMHang',
        'buyer_tax_code_value': 'NMua.MST',
        'buyer_tel_value': 'NMua.SDThoai',
        'seller_address_value': 'NBan.DChi',
        'seller_company_name_value': 'NBan.Ten',
        'seller_tax_code_value': 'NBan.MST',
        'seller_tel_value': 'NBan.SDThoai',
        'date_value': 'NLap',
        'form_value': 'KHMSHDon',
        'no_value': 'SHDon',
        'serial_value': 'KHHDon',
        'tax_amount_value': 'TToan.TgTThue',
        'total_in_words_value': 'TToan.TgTTTBChu',
        'total_value': 'TToan.TgTTTBSo'
    }

    converted_dict = {}
    for key, value in original_dict.items():
        new_key = key_mapping.get(key, key)
        if "." in new_key:
            parts = new_key.split(".")
            current_dict = converted_dict
            for i, part in enumerate(parts):
                if i == len(parts) - 1:
                    current_dict[part] = value
                else:
                    current_dict.setdefault(part, {})
                    current_dict = current_dict[part]
        else:
            if key == "table":
                lconverted_table_values = []
                for table_value in value:
                    converted_table_value = convert_key_names(table_value)
                    lconverted_table_values.append(converted_table_value)
                converted_dict[new_key] = lconverted_table_values
            else:
                converted_dict[new_key] = value

    return converted_dict