#!/usr/bin/python3
import subprocess
import json
import sys
import time

class ID:
    def __init__(self, args=''):
           self.app(args)

    def idEye3(self):
        data = subprocess.check_output(["grep","-nrw","/etc/eye3/config.php","-e","robot"]).decode()
        tcp = int(data.split(":")[2])
        return '{:04.0f}'.format((tcp - 10000) )# Mother/Jarvis product ID

    def nameEye3(self):
        data = subprocess.check_output(["grep","-nrw","/etc/eye3/config.php","-e","name"]).decode()
        data = data.split("'")[3].strip()
        return data.strip()
    
    def comando(self,orden):
        orden_s=orden.split(' ')
        res=subprocess.check_output(orden_s)
        if res.decode()!='\n' or res.decode()!='':
            print(res.decode())

    def reemplazar(self,ruta_archivo, texto_out, texto_in):
        with open(ruta_archivo,'r') as archivo:
            contenido=archivo.read()
        contenido_2 = contenido.replace(texto_out,texto_in)

        with open(ruta_archivo, 'w') as archivo_nuevo:
            archivo_nuevo.write(contenido_2)

    def id(self):
        res=subprocess.check_output('machineid').decode()
        return '{:04.0f}'.format(int(res))

    def nombre(self):
        res=subprocess.check_output('machinename').decode()
        return res.strip()
    
    def auto(self):
        while True:
            if self.nombre()!=self.nameEye3() or self.id()!=self.idEye3():
                self.reemplazar('/etc/mining/config.json',self.nombre(),self.nameEye3())
                self.reemplazar('/etc/mining/config.json',str(int(self.id())),str(int(self.idEye3())))
            time.sleep(3)

    def cambiar_nombre(self):
        while True:
            sel1 = input('Ingrese nuevo nombre: ')
            sel2 = input('Verifique nuevo nombre: ')
            if sel1==sel2:
                self.reemplazar('/etc/eye3/config.php',self.nameEye3(), sel1)
                self.reemplazar('/etc/mining/config.json', self.nombre(), sel1)
                break
            else:
                print('Error de coincidencia\n')

    def cambiar_id(self):
        while True:
            sel1 = input('Ingrese nuevo ID: ')
            sel2 = input('Verifique nuevo ID: ')
            if sel1==sel2:
                self.reemplazar('/etc/eye3/config.php',self.idEye3(), '{:04.0f}'.format(int(sel1)))
                self.reemplazar('/etc/mining/config.json', str(int(self.id())), str(int(sel1)))
                break
            else:
                print('Error de coincidencia\n')
    
    def app(self, args):
        if args == '-a':
            try:
                self.auto()
            except:
                print('Error reemplazando nombre o id')
        else:
            self.comando('clear')
            print('Sistema de Gestion de Nombre e ID\n')
            while True:
                print('\nNombre Eye3: '+self.nameEye3())
                print('ID Eye3: '+str(self.idEye3()))
                print('Nombre Mining: '+self.nombre())
                print('ID Mining: '+self.id()+'\n')

                sel=input('Seleccione Tarea a realizar:\n \n1. Cambiar Nombre\n2. Cambiar ID\n3. Autoanalizar\n4. Salir\n\nIngrese opcion: ')
                
                if sel=='1':
                    self.cambiar_nombre()
                elif sel=='2':
                    self.cambiar_id()
                elif sel=='3':
                    self.auto()
                else: break
                  
try:
    args = sys.argv[1]
    datalogger = ID(args)
except:
    datalogger = ID()
    
