#!/usr/bin/python3


import json
# from db import *
from globalSettings import *
from global_func import *
import cgi
import cgitb
import subprocess
cgitb.enable()
from datetime import datetime
import re
import sqlite3
conn = sqlite3.connect(DBPath)
conn.text_factory = str
c = conn.cursor()

# if (GUI == true):
form = cgi.FieldStorage()
request_Type = form.getvalue('requestType')
DeviceName = wavelengthRange
print("Content-type:/text/html\r\n\r\n")

def get_uptime():
    process1 = subprocess.check_output(['uptime','-p']).decode("utf8").replace(',', '')
    return convert_time_duration(process1)

def convert_time_duration(duration_str):
    # Extract the numbers from the input string
    numbers = re.findall(r'\d+', duration_str)

    # Convert the numbers to integers
    numbers = [int(num) for num in numbers]

    # Assign the extracted numbers to variables
    week = 0
    days = 0
    if len(numbers) <= 1:
        minutes = numbers[:1]
        formatted_str = "up {} min(s)".format(minutes)
    elif len(numbers) <= 2:
        hours, minutes = numbers[:2]
        formatted_str = "up {} hr(s) {} min(s)".format(hours, minutes)
    elif len(numbers) <= 3:
        days,hours, minutes = numbers[:3]
        formatted_str = "up {} day(s) {} hr(s) {} min(s)".format(days, hours, minutes)
    elif len(numbers) <=4:
        week, days, hours, minutes = numbers[:4]
        formatted_str = "up {} wk(s) {} day(s) {} hr(s) {} min(s)".format(week, days, hours, minutes)
    else:
        month,week, days, hours, minutes = numbers
        formatted_str = "up {} mo(s) {} wk(s) {} day(s) {} hr(s) {} min(s)".format(month, week, days, hours, minutes)

    # Construct the formatted string

    return formatted_str

def get_boottime():
    try:
        process1 = subprocess.check_output(['ls','-la',"/mnt/data/boot.crm"]).decode("utf8").replace(',', '')
        file_parts = process1.split()
        date_time_string = ' '.join(file_parts[5:8])
        date_time_string_with_year = date_time_string
        date_time = datetime.strptime(date_time_string_with_year, '%b %d %Y')
        formatted_date_time = date_time.strftime('%b %d %Y')
        return {"message": format_time_difference(formatted_date_time),"status": 200}
    except Exception as e:
        return {"message":"Not Available !!","status": 400}
def format_time_difference(timestamp):
    current_time = datetime.now()
    given_time = datetime.strptime(timestamp, '%b %d %Y')
    time_difference = current_time - given_time

    days = time_difference.days
    hours = time_difference.seconds // 3600
    minutes = (time_difference.seconds // 60) % 60

    formatted_time = "{} day(s) {} hr(s) {} min(s) ago".format(days, hours, minutes)
    return formatted_time 
def read_CCM():
    cmd_Id = get_ccm_command_id()
    if CCM:
        cmd="test_response"
        name="CCM"
        action="CCM"
        message="set,element=test_response,element_name={0},args=2,action={1},uuid={2}".format(name,action,cmd_Id)
        send_ccm_msg(message) 
        response = get_ccm_response(cmd_Id)
        delete_ccm_response(cmd_Id)
        #response = json.JSONEncoder().encode({"status": "success", "description": "CCM state: OK, License state: OK"})
        return response
    else:
        return json.JSONEncoder().encode({"status": "fail", "description": "CCM socket not active"})
def status():
    result = json.loads(read_CCM())
    if result["status"] == "fail":
        CCM = 0
    else:
        CCM = 1
    try:
        fwversion = c.execute("select fw_name from versionControl where status ='True'").fetchone()[0]
    except:
        fwversion = "fw12122023"
    response = {"health_status": 1,"softwareVersion" : SoftwareVersion,"buildVersion" : fwversion,"systemTime": get_uptime(),'device':DeviceName,"software_status" : CCM,"bootTime":get_boottime()}
    print((json.JSONEncoder().encode(response)))

if(request_Type == 'status'):
    status()