import socket
import sys
import time 
from array import *
import logging
import subprocess
from subprocess import call
import os
sys.path.insert(0,  '/../../../cgi')
# from globalSettings import uds_socket_path, ccm_response_path
from all_paths import *




def mydelete_file(uuid):
        if debug==0:
                return
        else:
                ccm_response_file=uuid+"ccm_response.txt"
                cmd_rm= "rm -rf "+ccm_response_file
                os.remove(ccm_response_file)
        return
#os.system(cmd_rm)

def check_file(uuid):
        if debug==0:
                return
        else:
                ccm_response_file=uuid+"ccm_response.txt"

        if os.path.isfile(ccm_response_file):
                print("Response File is present1")
        else:
                print("Response File is Absent1")

        return


logging.basicConfig(filename="client.log",format="%(asctime)s  %(levelname)s  %(message)s",level=logging.DEBUG,datefmt="%d/%m/%Y-%H:%M:%S%p")

# CcmMessage = b""
message = ' '.join(sys.argv[1:])
CcmMessage = str.encode(message)

# print(CcmMessage)

debug=0
#CcmMessage = b"</msg>0044set element=Timer,element_name=Timer1</msg>"
#print "CcmMessage from cgi_client.py",CcmMessage
logging.info("connecting to the server:")
sock=socket.socket(socket.AF_UNIX,socket.SOCK_STREAM)
server_address=uds_socket_path
logging.debug('connecting to %s'%server_address)
try:
	sock.connect(server_address)
except (socket.error,msg):
	logging.debug(msg)
	print("socket open error")
	sys.exit(1)

logging.debug(CcmMessage)
sock.send(CcmMessage)

uuid=b"1234"
#extract UUID
index=CcmMessage.find(b"uuid")
if (index!=-1):
	uuid=str(CcmMessage[index+5:index+9])
if debug==1:
    	uuid="1234"

ccm_response_file=ccm_response_path+uuid+"ccm_response.txt"
# ccm_response_file=response_txt_path+uuid+"ccm_response.txt"
mydelete_file(uuid)
check_file(uuid)
fo = open(ccm_response_file,"w")
time.sleep(.5)
response = b""
CcmResponse=sock.recv(8192)
response += CcmResponse
logging.debug(CcmResponse+b"\n"	)
#CcmResponse = str(CcmResponse)
CcmResponse = CcmResponse.decode()
#testResponse= '{"status": "Test", "Description": "Divya Test Updated Network"}'
logging.info("Writing response file ")
# print(type(CcmResponse), "type")
fo.write(CcmResponse);
fo.close()
logging.info("Closing the socket exit ")
sock.close()
	

