'''
Script to set the URL for a HTTP request and trigger the POST Request
Ex:
/usr/bin/python3 /var/www/nebuleair_pro_4g/SARA/SSL/test_22.py ttyAMA2 api-prod.uspot.probesys.net /nebuleair?token=2AFF6dQk68daFZ
/usr/bin/python3 /var/www/nebuleair_pro_4g/SARA/SSL/test_22.py ttyAMA2 webhook.site /6bee2237-099a-4ff4-8452-9f4126df7151
/usr/bin/python3 /var/www/nebuleair_pro_4g/SARA/SSL/test_22.py ttyAMA2 aircarto.fr /tests/test.php
/usr/bin/python3 /var/www/nebuleair_pro_4g/SARA/SSL/test_22.py ttyAMA2 ssl.aircarto.fr /test.php
/usr/bin/python3 /var/www/nebuleair_pro_4g/SARA/SSL/test_22.py ttyAMA2 vps.aircarto.fr /test.php



First profile id:
    AT+UHTTP=0,1,"data.nebuleair.fr"
Second profile id:
    AT+UHTTP=1,1,"api-prod.uspot.probesys.net"
Third profile id:
    AT+UHTTP=2,1,"aircarto.fr"

'''

import serial
import time
import sys
import json

parameter = sys.argv[1:]  # Exclude the script name
#print("Parameters received:")
port='/dev/'+parameter[0] # ex: ttyAMA2
url = parameter[1]  # ex: data.mobileair.fr
endpoint = parameter[2]
profile_id = 3

#get baudrate
def load_config(config_file):
    try:
        with open(config_file, 'r') as file:
            config_data = json.load(file)
        return config_data
    except Exception as e:
        print(f"Error loading config file: {e}")
        return {}

# Define the config file path
config_file = '/var/www/nebuleair_pro_4g/config.json'
# Load the configuration data
config = load_config(config_file)
# Access the shared variables
baudrate = config.get('SaraR4_baudrate', 115200)
send_uSpot = config.get('send_uSpot', False) 

def color_text(text, color):
    colors = {
        "red": "\033[31m",
        "green": "\033[32m",
        "yellow": "\033[33m",
        "blue": "\033[34m",
        "magenta": "\033[35m",
        "cyan": "\033[36m",
        "white": "\033[37m",
    }
    reset = "\033[0m"
    return f"{colors.get(color, '')}{text}{reset}"

def read_complete_response(serial_connection, timeout=2, end_of_response_timeout=2, wait_for_line=None):
    response = bytearray()
    serial_connection.timeout = timeout
    end_time = time.time() + end_of_response_timeout
    start_time = time.time()
 
    while True:
        elapsed_time = time.time() - start_time  # Time since function start
        if serial_connection.in_waiting > 0:
            data = serial_connection.read(serial_connection.in_waiting)
            response.extend(data)
            end_time = time.time() + end_of_response_timeout  # Reset timeout on new data

            # Decode and check for the specific line
            if wait_for_line:
                decoded_response = response.decode('utf-8', errors='replace')
                if wait_for_line in decoded_response:
                    print(f"[DEBUG] 🔎Found target line: {wait_for_line}")
                    break
        elif time.time() > end_time:
            print(f"[DEBUG] Timeout reached. No more data received.")
            break
        time.sleep(0.1)  # Short sleep to prevent busy waiting
    # Final response and debug output
    total_elapsed_time = time.time() - start_time
    print(f"[DEBUG] ⏱️ elapsed time: {total_elapsed_time:.2f}s. ⏱️")
    return response.decode('utf-8', errors='replace')

ser_sara = serial.Serial(
    port=port,  #USB0 or ttyS0
    baudrate=baudrate, #115200 ou 9600
    parity=serial.PARITY_NONE, #PARITY_NONE, PARITY_EVEN or PARITY_ODD
    stopbits=serial.STOPBITS_ONE,
    bytesize=serial.EIGHTBITS,
    timeout = 2
)


try:


    #check certificate (List all available certificates and private keys)
    print("\033[0;33mCheck certificate\033[0m")
    command = f'AT+USECMNG=3\r'
    ser_sara.write((command + '\r').encode('utf-8'))
    response_SARA_5b = read_complete_response(ser_sara, wait_for_line="OK")
    print(response_SARA_5b)
    time.sleep(0.5)

    #security layer
    
    #1
    print("\033[0;33mCheck certificate\033[0m")
    command = f'AT+USECPRF=<profile_id>,<op_code>\r'
    ser_sara.write((command + '\r').encode('utf-8'))
    response_SARA_5b = read_complete_response(ser_sara, wait_for_line="OK")
    print(response_SARA_5b)
    time.sleep(0.5)



except serial.SerialException as e:
    print(f"Error: {e}")

finally:
    if ser_sara.is_open:
        ser_sara.close()
        print("****")
        #print("Serial closed")

