#!/usr/bin/python3
import socket
import sys
import time
from array import *
import logging
import subprocess
from subprocess import call
import os
#from db import *
from globalSettings import *
#import sqlite3
import string
import random
import json
device = DeviceName

response_txt_path = "/home/"
# add_validate function is for ethernet ports ipv4 validations

def cfgValidate(address):
    ip_addr = address.split(".")
    if len(ip_addr) == 4:
        for i in ip_addr:
            if i.isdigit() and int(i) in range(0, 256):
                res = True
                continue

            else:
                #res="All Values should be Numericals and must be in the range 0-255"
                res = False
                break

    else:
        #res="Address should be in the format of x.y.z.a.(e.x: 192.168.1.1)"
        res = False
    return res


def ccm_msg_length(message):
    length = "0000"
    tail = "</msg>"
    length_message = len(message)
    length_message = length_message+len(tail)  # add in the tail length </msg>
    if length_message <= 9:
        k = length.rfind("0")
    elif length_message <= 99:
        k = length.rfind("00")
    elif length_message <= 999:
        k = length.rfind("000")
    msg_length = length[:k]+str(length_message)
    return msg_length


def send_ccm_msg(message):
    try:
        msg_length = ccm_msg_length(message)
        #dataHeader = </msg>msg_length
        #databody="set element={},element_name={}...."
        #we should be able to see above in the server_thread.py
        #cgi_client.py gets the message from here
        socket_cmd = "</msg>{0}{1}</msg>".format(msg_length, message)
        socket_msg = bytes(socket_cmd,'utf-8')

        process1 = subprocess.call([CGIpath, socket_cmd])
    except Exception as e:
        pass


def get_ccm_response(uuid):
    try:
        filename = "ccm_response.txt"
        ccm_response_file = ccm_response_path+'b'+"'"+str(uuid)+"'"+filename
        # ccm_response_file = "/var/www/"+'b'+"'"+str(uuid)+"'"+filename

        file = 0
        while (file < 100):
            if os.path.isfile(ccm_response_file):
                file = 101
            else:
                file = file+1
                time.sleep(.1)
        #print(ccm_response_file)
        # fo = open( os.path.expanduser(ccm_response_file), "r")
        fo = open(ccm_response_file, "r")
        CcmResponse = fo.read()
        fo.close()
        return CcmResponse
    except Exception as e:
        return json.JSONEncoder().encode({"description":"CCM socket is not active","status":"fail"})


def id_generator(size=4, chars=string.ascii_uppercase + string.digits):
    return ''.join(random.choice(chars) for _ in range(size))


def get_ccm_command_id():
    command_id = id_generator()
    return (command_id)


def delete_ccm_response(uuid):
    try:
        filename = "ccm_response.txt"
        # ccm_response_file = gui_path+str(uuid)+filename
        ccm_response_file = ccm_response_path+'b'+"'"+str(uuid)+"'"+filename

        # cmd_rm = "sudo rm -rf "+ccm_response_file
        os.remove(ccm_response_file)
        # os.system(cmd_rm)
    except Exception as e:
        pass

def is_ccm_running(process_name):
    global CCM
    try:
        output = subprocess.check_output(['ps', 'aux'], universal_newlines=True)
        for line in output.splitlines():
            if process_name in line and 'grep' not in line:
                CCM = 1
                return True
        CCM = 1
        return False
    except subprocess.CalledProcessError:
        CCM = 1
        return False

# Checking CCM is running or not
if CCM_Check == true:
    is_ccm_running("main.py")
else:
    CCM = 0 