#!/usr/bin/python3
import subprocess
import json
print('Configuracion de EVO\n')
CONFIG_SOURCE = "/srv/datalogger_ecom/config_ecom.json"
try:
    update_flag = False  
    config_file=open(CONFIG_SOURCE,'r')
    config=json.load(config_file)
    lista_evo = config["DUST_SENSOR"]["EVOS"]
    if len(lista_evo)==0:
        print('NO HAY NINGUN EVO AGREGADO')

    else:

        print("Lista de EVOS Configurados: \n")
        for i in range(len(lista_evo)):
            print(str(i+1)+". "+lista_evo[i])

    while True:
        sel=input("Desea Consultar (C), Agregar (A) o Remover (R) un EVO? o (Q) para salir: ")
        try:
            if sel=='A' or sel=='a':
                nombre=input('Ingrese nombre de Evo: ')
                lista_evo.append(nombre)
                config["DUST_SENSOR"]["AUTOUPDATE_EVO"]= 0 # Se cambia autoupdate a 1, ya que se configuro manualmente
                update_flag = True               
                print('Evo ' + nombre + ' agregado. Para salir presione (Q)\n')

            elif sel=='R' or sel=='r':
                if len(lista_evo)==0:
                    print('NO HAY NINGUN EVO AGREGADO')
                else:
                    print("Seleccione un EVO\n")
                    for i in range(len(lista_evo)):
                        print(str(i+1)+". "+lista_evo[i])
                    sel2=input('EVO SELECCIONADO: ')
                    lista_evo.pop(int(sel2)-1)
                    config["DUST_SENSOR"]["AUTOUPDATE_EVO"]= 0 # Se cambia autoupdate a 1, ya que se configuro manualmente
                    update_flag = True    
                    print('Evo eliminado. Para salir presione (Q)\n')

            elif sel=='C' or sel=='c':
                if len(lista_evo)==0:
                    print('NO HAY NINGUN EVO AGREGADO')
                else:
                    print("EVOs\n")
                    for i in range(len(lista_evo)):
                        print(str(i+1)+". "+lista_evo[i])
                print('Para salir presione (Q)\n')

            elif sel=='Q' or sel=='q':
                break

            else:
                print("Ingrese un valor valido")

        except:
            print("Ingrese un valor valido")
    
    try:
        #ESCRIBIR JSON
        if update_flag:
            with open(CONFIG_SOURCE,'w') as archivo:
                config["DUST_SENSOR"]["EVOS"] = lista_evo
                json.dump(config, archivo, indent=len(config))
            print("Archivo de configuración actualizado")
            out1 = subprocess.check_output(['systemctl','restart','mining-serial.service'])
    except:
        print("No se pudo sobreescribir el json")

except:
    print("No existe archivo config_ecom.json")
