
#  *
#  * Convierte los archivos xml a json
#  * 
#  * @author: Marc Henales
#  * @version: 1.0
#  * @created: 24/04/2025
#  *

import os
import xml.etree.ElementTree as ET
import json
import shutil
import datetime
import requests

#* Ruta de la carpeta que contiene los archivos XML
carpeta = './temp'

#* Función para simplificar XML a JSON
def xml_to_json(element, include_ns=False):
    
    json_dict = {}

    #* Manejar atributos del elemento
    if element.attrib:
        json_dict.update({""+ k + "": v for k, v in element.attrib.items()})

    #* Capturar contenido de texto si existe
    if element.text and element.text.strip():
        json_dict["#*text"] = element.text.strip()

    #* Iterar sobre los hijos del elemento
    for child in element:
        #* Obtener la etiqueta (con o sin namespace)
        tag = child.tag if include_ns else child.tag.split('}')[-1]

        #* Convertir recursivamente el hijo a JSON
        value = xml_to_json(child, include_ns)

        #* Manejar elementos duplicados como listas
        if tag in json_dict:
            if not isinstance(json_dict[tag], list):
                json_dict[tag] = [json_dict[tag]]  #* Convertir en lista si no lo es
            json_dict[tag].append(value)
        else:
            json_dict[tag] = value

    return json_dict

#* Función para procesar cada archivo XML
def procesar_xml(archivo):
    try:
        tree = ET.parse(archivo)
        root = tree.getroot()

        #* Convertir XML a JSON
        json_data = xml_to_json(root)

        #* Extraer el ID único de la reserva
        unique_id = None
        for elem in root.iter():
            if 'UniqueID' in elem.tag:
                unique_id = elem.attrib.get('ID')
                break

        if unique_id:
            json_data['UniqueID'] = unique_id

        #* Datos XML
        archivo_xml = archivo
        nombre_xml = os.path.basename(archivo_xml)

        if "MODIFICATION" in nombre_xml:
            nombre_xml = "MODIFICATION.xml"
        elif "NEW" in nombre_xml:
            nombre_xml = "NEW.xml"
        else:
            nombre_xml = "CANCELLATION.xml"

        #* Datos JSON
        archivo_json = os.path.splitext(archivo)[0] + '.json'
        nombre_json = os.path.basename(archivo_json)

        if "MODIFICATION" in nombre_json:
            nombre_json = "MODIFICATION.json"
        elif "NEW" in nombre_json:
            nombre_json = "NEW.json"
        else:
            nombre_json = "CANCELLATION.json"

        #* Guardo Año/Mes (currentDate)
        year = datetime.datetime.strftime(datetime.datetime.now(), '%Y')
        month = datetime.datetime.strftime(datetime.datetime.now(), '%m')

        #* Crear carpetas por Año/Mes si no existen
        os.makedirs(os.path.join("./json", year, month), exist_ok=True)
        os.makedirs(os.path.join("./xml", year, month), exist_ok=True)

        #* Construir rutas de destino
        if unique_id:
            destino_json = os.path.join(
                "./json", year, month, unique_id + "_" + nombre_json)
            destino_xml = os.path.join(
                "./xml", year, month, unique_id + "_" + nombre_xml)
        else:
            destino_json = os.path.join("./json", year, month, nombre_json)
            destino_xml = os.path.join("./xml", year, month, nombre_xml)

        #* Hacemos una petición a GHOT
        url = 'http://10.11.200.153/ghot/booking_notification_ots'

        #* Convertir json_data a una cadena de texto JSON
        json_data_str = json.dumps(json_data)

        #* Datos de la petición
        data = {
            'test': 0,
            'file': unique_id + "_" + nombre_json,
            'json': json_data_str
        }

        #* Hacer la petición POST
        response = requests.post(url, data=data)

        #* Verificar el estado de la respuesta
        if response.status_code == 200:
            if response.text == "1":
                try:
                    #* Guardar JSON
                    with open(archivo_json, 'w') as json_file:
                        json.dump(json_data, json_file, indent=4)
                    #* Movemos a carpetas correspondientes
                    shutil.move(archivo_json, destino_json)
                    shutil.move(archivo_xml, destino_xml)
                except Exception as e:
                    print("Error al mover archivos: " + e)
        else:
            print("Error: " + response.status_code)

    except ET.ParseError as e:
        print("Error al procesar " + archivo + ": " + e)


#* Recorrer todos los archivos en la carpeta
for nombre_archivo in os.listdir(carpeta):
    if nombre_archivo.endswith('.xml'):
        ruta_archivo = os.path.join(carpeta, nombre_archivo)
        procesar_xml(ruta_archivo)
