#!/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
try:
    import psutil
except Exception as e:
    print(json.JSONEncoder().encode({"status": "fail", "description": "psutil not installed, To Install Run 'sudo pip3 install psutil'"}))
    exit()
import sqlite3
conn = sqlite3.connect(DBPath)
conn.text_factory = str
c = conn.cursor()

# if (GUI == true):
form = cgi.FieldStorage()
request_Type = form.getvalue('requestType')
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 disk_usage(path):
    hdd = psutil.disk_usage(path)
    size=(hdd.free)
    size=size/(1024**3)
    return size

import subprocess
import psutil
import platform

def getTotalMemoryCapacity():
    try:
        system = platform.machine().lower()
        total_gb = 0

        if "x86" in system or "amd64" in system:
            try:
                output = subprocess.check_output(
                    ["sudo", "dmidecode", "-t", "17"]
                ).decode("utf-8").splitlines()

                for line in output:
                    line = line.strip()
                    if line.startswith("Size:") and "MB" in line:
                        size_mb = int(line.replace("Size:", "").replace("MB", "").strip())
                        total_gb += size_mb / 1024
                    elif line.startswith("Size:") and "GB" in line:
                        size_gb = int(line.replace("Size:", "").replace("GB", "").strip())
                        total_gb += size_gb

            except Exception:
                total_gb = psutil.virtual_memory().total / (1024**3)

        else:
            with open("/proc/meminfo", "r") as f:
                meminfo = f.read()

            for line in meminfo.splitlines():
                if line.startswith("MemTotal:"):
                    kb = int(line.split()[1])       # value is in KB
                    total_gb = kb / (1024**2)
                    break

        mem = psutil.virtual_memory()

        used_gb = round(mem.used / (1024**3), 2)
        total_os_gb = round(mem.total / (1024**3), 2)
        free_gb = round(total_os_gb - used_gb, 2)

        data = {
            "capacity": f"{round(total_gb, 2)} GB",
            "total": total_os_gb,
            "used": used_gb,
            "free": free_gb
        }

        return data

    except Exception as e:
        return {"error": str(e)}
  

def status():
    try:
        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 = BuildVersion

        path=('/mnt/data')
        free=disk_usage(path)
        data_freespace=str(format(free, '.2f'))

        path=('/mnt/xdata')
        free=disk_usage(path)
        xdata_freespace=str(format(free, '.2f'))

        response = {"health_status": 1,"softwareVersion" : SoftwareVersion,"buildVersion" : fwversion,"systemTime": get_uptime(),'device':DeviceName,"software_status" : CCM,"bootTime":get_boottime(),"data_freespace":data_freespace,"xdata_freespace":xdata_freespace , "memory_capacity" : getTotalMemoryCapacity(), "status" : "success"}
        print((json.JSONEncoder().encode(response)))
    except Exception as e:
        print(json.JSONEncoder().encode({"status": "fail", "description": str(e)}))

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