#!/usr/bin/python3
import subprocess
import json
import os

SOURCE_GEOFENCE = "/srv/datalogger_mmr/geofence.json"
SOURCE_CONFIG = "/srv/datalogger_mmr/config_mmr.json"
HEADER= '--header="X-Device-Key:8b52dd9bd5f0ae78c502a2b5f332b25d7449af29500f619689ed82cb016f14be"'

def update_config(source_config, config):
    try:
        #ESCRIBIR JSON
        with open(source_config, "w") as f:
            json.dump(config, f, indent=len(config))
    except:
        print("No se pudo sobreescribir el json")

def command(orden):
    orden_s=orden.split(' ')
    res=subprocess.check_output(orden_s)
    if res.decode()!='\n' or res.decode()!='':
        print(res.decode())

def show_current_config(config):
    current_tablet = config["TABLET"]
    for key, value in current_tablet.items():
        print(f"{key}: {value}")
    print(f'Voltaje minimo configurado: {config["VALVE_SENSOR"]["LEVEL_CURVE"][0]} [V]')
    print(f'Voltaje maximo configurado: {config["VALVE_SENSOR"]["LEVEL_CURVE"][1]} [V]')
    print("\n\n")


def update_geofence(faena:str, source_geofence, header):
    try:
        api_url = f'https://{faena.replace(" ", "").lower()}.mapa.mine-360.com/api/geofence'
        if api_url:
            source_raw_geofence = "/srv/datalogger_mmr/raw_geofence.json"
            geofence_cmd = f'wget --header="X-Device-Key:{header}" {api_url} -O {source_raw_geofence}'

            print(f"Downloading GEOFENCE geometry from: {api_url}")
            print("[%s] ..." % geofence_cmd)
            print(os.popen(geofence_cmd).read())

            try:
                raw_geofence =json.load(open(source_raw_geofence))
                if "ok" in raw_geofence:
                    print("Geofence tiene la nueva estructura, cambiando ...")
                    # Cambiar la estructura
                    geofence = raw_geofence["data"][0]["row_to_json"]
                    with open(source_geofence, "w") as f:
                        json.dump(geofence, f)
                    print("Geofence guardada con estructura corregida")

                else:
                    print("Estructura geofence correcta!")
                    geofence = raw_geofence
                    with open(source_geofence, "w") as f:
                        json.dump(geofence, f)
                    print("Geofence guardada")

            except:
                print("Error procesando geofence")

            # update tablet geofence
            print("Updating tablet geofence...")
            tablet_cmd = f"cp {source_geofence} /var/www/html/caminos.geojson"
            command(tablet_cmd)

            print("update_geofence(): Done")
        else:
            print("No existe url para descarga de geofence")
    except Exception as ex:
        print(ex)
        print("Error actualizando geofence")

def update_html(faena):
    try:
        faena = faena.replace(" ", "")
        path_current_index = "/var/www/html/index.html"
        path_base_index = f"/srv/datalogger_mmr/tablet/htmls/{faena}.html"
        cmd = f"cp {path_base_index} {path_current_index}"
        command(orden = cmd)
        print("update_html: Done")
    except Exception as ex:
        print(ex)
        print("Error actualizando html")

def update_config_urls(faena, source_config=SOURCE_CONFIG):
    try:
        faena_clean = faena.replace(" ", "").lower()
        config_path = source_config

        # Cargar JSON
        with open(config_path, "r") as f:
            config = json.load(f)

        avalaible_faenas = ["Antucoya", "Candelaria", "Centinela", "Ministro Hales"]
        coords = {"antucoya": [-22.633667,-69.877167], "candelaria": [-27.519101,-70.289366], "centinela": [-23.003623528779894,-69.08605917310669], "ministrohales": [-22.38916, -68.916165]}

        if faena in avalaible_faenas:
            base = f"https://{faena_clean}.mapa.mine-360.com/api"
        else:
            base = ""

        config["TABLET"]["API_URL_REG"] = f"{base}/vehicles/reg" if base else ""
        config["TABLET"]["API_PM100_FILTRADO"] = f"{base}/tablets/pm100_filtrado" if base else ""
        config["TABLET"]["API_RIEGO"] = f"{base}/riego" if base else ""
        config["TABLET"]["GEOFENCE_PATH"] = "/srv/datalogger_mmr/geofence.json"
        config["TABLET"]["X_COORD"] = coords[faena_clean][0]
        config["TABLET"]["Y_COORD"] = coords[faena_clean][1]

        # Guardar JSON
        update_config(config_path, config)

        print("update_config_urls(): Done")
        out = subprocess.check_output(['systemctl','restart','mining-server-html'])

    except Exception as ex:
        print("Error actualizando URLs del config:", ex)


def update_map(faena, source_geofence, header):
    # 1. Update Geofence
    update_geofence(faena, source_geofence, header)

    # 2. Update HTML
    update_html(faena)

    # 3. Update config URLs
    update_config_urls(faena)


def app(source_geofence, source_config):
    command('clear')
    print("Configuraciones Actuales Mapa:")
    try:
        config_file=open(source_config,'r')
        config=json.load(config_file)
        show_current_config(config)

        while True:
            sel=input('Seleccione Tarea a realizar:\n \n1. Actualizar HTML y Geofence\n2. Configurar Sensor para Nivel\n3. Activar o Desactivar Visualización de Volumen\n4. Mostrar configuración Actual\n5. Salir\n\nIngrese opcion: ')
            try:

                # 1. Actualizar de forma manual html y geofence
                if sel=='1':
                    print('sistema de actualización manual de mapa\n')
                    sel=input('Seleccione Faena:\n \n1. Antucoya\n2. Candelaria\n3. Centinela\n4. Ministro Hales\n5. Salir\n\nIngrese opcion: ')
                    if sel=='1':
                        faena = "Antucoya"
                    elif sel=='2':
                        faena = "Candelaria"
                    elif sel=='3':
                        faena = "Centinela"
                    elif sel=='4':
                        faena= "Ministro Hales"
                    elif sel=='5':
                        return
                    else:
                        print("Opción no valida")
                        return

                    update_map(faena, source_geofence ,config['API_TOKEN'])

                # 2. Configurar Sensor de Nivel
                elif sel=='2':
                    print("Seleccione sensor a configurar:")
                    print("1- SATEL")
                    print("2- TUF")
                    print("3- DESACTIVAR VISUALIZACIÓN DE SENSOR DE NIVEL EN EL MAPA")
                    sel_option=input("Ingrese la opcion 1, 2 o 3: ")
                    if sel_option =="1":
                        voltage=input("Ingrese Voltaje Minimo (parte decimal separada por punto):")
                        v_min = float(voltage)
                        voltage=input("Ingrese Voltaje Maximo (parte decimal separada por punto):")
                        v_max = float(voltage)

                        config["TABLET"]["SHOW_LEVEL"] = True
                        config["TABLET"]["MODEL_SENSOR_LEVEL"] = "SATEL"
                        config["VALVE_SENSOR"]["LEVEL_CURVE"] = [v_min, v_max]

                        update_config(source_config, config)

                        out1 = subprocess.check_output(['systemctl','restart','mining-serial.service'])
                        out1 = subprocess.check_output(['systemctl','restart','mining-flow.service'])
                        out1 = subprocess.check_output(['systemctl','restart','apache2.service'])
                        print("VISUALIZACIÓN DE NIVEL ACTIVADA A PARTIR DEL SENSOR DE SATEL\n\n")

                    elif sel_option =="2":
                        config["TABLET"]["SHOW_LEVEL"] = True
                        config["TABLET"]["MODEL_SENSOR_LEVEL"] = "TUF"
                        update_config(source_config, config)

                        out1 = subprocess.check_output(['systemctl','restart','mining-serial.service'])
                        out1 = subprocess.check_output(['systemctl','restart','mining-flow.service'])
                        out1 = subprocess.check_output(['systemctl','restart','apache2.service'])
                        print("VISUALIZACIÓN DE NIVEL ACTIVADA A PARTIR DEL CALCULO DE FLUJO DE SENSOR TUF\n\n")

                    elif sel_option =="3":
                        config["TABLET"]["SHOW_LEVEL"] = False
                        config["TABLET"]["MODEL_SENSOR_LEVEL"] = ""
                        update_config(source_config, config)

                        out1 = subprocess.check_output(['systemctl','restart','mining-serial.service'])
                        out1 = subprocess.check_output(['systemctl','restart','mining-flow.service'])
                        out1 = subprocess.check_output(['systemctl','restart','apache2.service'])
                        print("VISUALIZACIÓN DE NIVEL DESACTIVADA\n\n")

                    else:
                        print("Ingrese un valor valido")

                # 3. Configurar Visualizacion de Volumen Acumulado
                elif sel=='3':
                    print("Seleccione si desea activar o desactivar la visualización de volumen en el mapa:")
                    print("1- ACTIVADO")
                    print("2- DESACTIVADO")
                    sel_status=input("Ingrese la opcion 1 o 2: ")
                    if sel_status =="1":
                        config["TABLET"]["SHOW_VOLUME"] = True
                        update_config(source_config, config)

                        out1 = subprocess.check_output(['systemctl','restart','mining-flow.service'])
                        out1 = subprocess.check_output(['systemctl','restart','apache2.service'])
                        print("VISUALIZACIÓN DE VOLUMEN ACTIVADA\n\n")

                    elif sel_status =="2":
                        config["TABLET"]["SHOW_VOLUME"] = False
                        update_config(source_config, config)

                        out1 = subprocess.check_output(['systemctl','restart','mining-flow.service'])
                        out1 = subprocess.check_output(['systemctl','restart','apache2.service'])
                        print("VISUALIZACIÓN DE VOLUMEN DESACTIVADA\n\n")

                    else:
                        print("Ingrese un valor valido\n\n")

                # 4. Mostrar Configuracion Actual
                elif sel=='4':
                    show_current_config(config)

                # 5. Salir
                elif sel=='5':
                    break

                else:
                    print("Ingrese un valor valido\n\n")

            except Exception as ex:
                print(ex)
                print("Ingrese un valor valido\n\n")

    except Exception as ex:
        print(ex)
        print("\n\n")


if __name__ == "__main__":
    app(SOURCE_GEOFENCE, SOURCE_CONFIG)