import json
import psycopg2
import psycopg2.extras
import sys
import aux_function as  aux
import requests
import time

def recuperar_bultos(cursor, almacen):
   url = cfg['interface']['recuperarBultos']+'/'+cfg['codigo_almacen']
   r = requests.get(url)
   if r.status_code == 200:
        data = r.json()
        for bulto in data:
            try:
                sql = f"INSERT INTO DHL_LINK_ID (warehouse_id, inventory_id, carrier, wave_name, position) VALUES ('{bulto['warehouse_id']}', '{bulto['inventory_id']}', '{bulto['carrier']}', '{bulto['wave_name']}', '{bulto['position']}')"
                cursor.execute(sql)
                if cursor.rowcount == 1:
                    urlMarcado = cfg['interface']['marcarBulto']+'/'+bulto['inventory_id']
                    r = requests.put(urlMarcado)
                    if r.status_code == 200:
                        print(f"[INFO] Se ha encontrado un bulto nuevo {bulto['inventory_id']}")
                        conn.commit()
                    else:
                        conn.rollback()
                        return False
            except psycopg2.errors.UniqueViolation as pk_error:
                urlMarcado = cfg['interface']['marcarBulto']+'/'+bulto['inventory_id']
                r = requests.put(urlMarcado)
                if r.status_code == 200:
                    conn.commit()
        return True

if __name__ == '__main__':
    try:
        jsonConfig = open('config.json')
        cfg = json.load(jsonConfig)
        jsonConfig.close()
    except Exception as e:
        aux.graba_log('config', 'Error al abrir o parsear el JSON de configuracion')
        sys.exit(1)

    try:
        db = cfg['db']
        conn = psycopg2.connect(db)
        cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    except:
        aux.graba_log('config', 'Error al abrir la base de datos SQLite')
        sys.exit(1)
    if conn is not None:
        contador = 69
        while True:
            print(f"[INFO][{contador}] Recuperando bultos")
            recuperar_bultos(cursor, cfg['codigo_almacen'])
            time.sleep(1)
            contador = contador + 1
            if contador >= 60:
                sql = f"UPDATE LOG_MOTORES SET MOMENTO = CURRENT_TIMESTAMP WHERE proceso = 'API'"
                cursor.execute(sql)
                conn.commit()
                contador = 0



