import json
import serial
import time

# Record the start time of the script
start_time = time.time()

# Define the path to the JSON file
file_path = "/var/www/nebuleair_pro_4g/loop/data.json"  # Replace with your actual file path

url="data.nebuleair.fr"

#get config
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)
device_id = config.get('deviceID', '').upper()
need_to_log = config.get('loop_log', False)

ser = serial.Serial(
    port='/dev/ttyAMA2',
    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
)

def read_complete_response(serial_connection, timeout=2, end_of_response_timeout=2):
    response = bytearray()
    serial_connection.timeout = timeout
    end_time = time.time() + end_of_response_timeout

    while True:
        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
        elif time.time() > end_time:
            break
        time.sleep(0.1)  # Short sleep to prevent busy waiting

    return response.decode('utf-8')

# Open and read the JSON file
try:
    with open(file_path, 'r') as file:
        # Load the data from the file
        data = json.load(file)
        
        # Print the content of the JSON file
        if need_to_log:        
            print("Data from JSON file:")
            print(json.dumps(data, indent=4))  # Pretty print the JSON data
        
        message = f"{data['PM1']},{data['PM25']},{data['PM10']}"

        #Write Data to saraR4
        #1. Open sensordata.json (with correct data size)
        size_of_string = len(message)
        command = f'AT+UDWNFILE="sensordata.json",{size_of_string}\r'
        ser.write((command + '\r').encode('utf-8'))
        response_SARA_1 = read_complete_response(ser)
        if need_to_log:        
            print("Open JSON:")
            print(response_SARA_1)
        time.sleep(1)
        #2. Write to shell
        ser.write(message.encode())
        response_SARA_2 = read_complete_response(ser)
        if need_to_log:        
            print("Write to memory:")
            print(response_SARA_2)
        #3. Send to endpoint (with device ID)
        command= f'AT+UHTTPC=0,4,"/pro_4G/data.php?sensor_id={device_id}","server_response.txt","sensordata.json",4\r'                                                                                            
        ser.write((command + '\r').encode('utf-8'))
        response_SARA_3 = read_complete_response(ser)
        if need_to_log:        
            print("Send data:")
            print(response_SARA_3)
            # Split response into lines
            lines = response_SARA_3.strip().splitlines()
                # +UUHTTPCR: <profile_id>,<http_command>,<http_result>
                # <http_result>: 1 pour sucess et 0 pour fail
                # +UUHTTPCR: 0,4,1 -> OK
                # +UUHTTPCR: 0,4,0 -> error

            # Extract HTTP response code from the last line
            http_response = lines[-1]  # "+UUHTTPCR: 0,4,0"
            parts = http_response.split(',')

            # Check HTTP result
            if len(parts) == 3 and parts[-1] == '0':  # The third value indicates success
                print("*****")
                print("!ATTENTION!")
                print("error: HTTP operation failed.")
                print("*****")
                print("resetting the URL (domain name):")
                command = f'AT+UHTTP=0,1,"{url}"\r'
                ser.write((command + '\r').encode('utf-8'))
                response_SARA_31 = read_complete_response(ser)
                if need_to_log:
                    print(response_SARA_31)

            else:
                print("HTTP operation successful.")
                #4. Read reply from server                                                                            
                ser.write(b'AT+URDFILE="server_response.txt"\r')              
                response_SARA_4 = read_complete_response(ser)
                if need_to_log:
                    print("Reply from server:")
                    print(response_SARA_4)

        #5. empty json
        ser.write(b'AT+UDELFILE="sensordata.json"\r')
        response_SARA_5 = read_complete_response(ser)
        if need_to_log:
            print("Empty JSON:")
            print(response_SARA_5)

    

        # Calculate and print the elapsed time
        elapsed_time = time.time() - start_time
        if need_to_log:
            print(f"Elapsed time: {elapsed_time:.2f} seconds")
            print("-----------------")

except Exception as e:
    print(f"Error reading the JSON file: {e}")