##
# Copyright (c) 2021 Xilinx, Inc.
# 
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and 
# associated documentation files (the "Software"), to deal in the Software without restriction, including 
# without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
# copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to 
# the following conditions: 
# 
# The above copyright notice and this permission notice shall be included in all copies or substantial 
# portions of the Software. 
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT 
# LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# 
#
#
##
#!/usr/bin/env python
import os,sys,inspect,importlib,json,datetime
import threading
from multiprocessing import Process

currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0,parentdir)
from api import users,settings
from backend import ysocket
from backend import tcpclient
# from backend import ysocket
from backend import header
from backend import rabbitmq_config
from backend import receiver
from pymongo import MongoClient
from time import sleep
import string
import logging

# reduce log level
connection=""
channel = ""

def myconverter(o):
    if isinstance(o, datetime.datetime):
        return o.__str__()

class PikaClient:
    def __init__(self, threadname="",command="",size=0,delay=0.5,sysstatus = True, socketdetails = "",active_client = ""):
        self.threadname = threadname
        self.command = command
        self.size = size
        self.socketdetails = socketdetails
        self.delay = delay
        self.sysstatus = sysstatus
        self.active_client = active_client

    def createthread(self):
        self.plotthread = threading.Thread(target=self.newconnection, args=())
        self.plotthread.deamon = True
        self.plotthread.start()

    def newconnection(self):
        # global connection, channel
        user = users.get_user(self.active_client, "connectionstatus")
        mongoClient = MongoClient(settings.MONGO_URI)
        while self.sysstatus and user["connectionstatus"]:
            user = users.get_user(self.active_client, "connectionstatus")
            message = self.getsysdata(self.command)
            receiver.dbdump(mongoClient,self.active_client, message)
            sleep(float(self.delay))
        print("closing channel")
        mongoClient.close()
        return 1

    def getsysdata(self,commandarr):
        sysArr = {"tabname": "syswatch","threadname":self.threadname,"command":self.command,"size":self.size, "data": [],"time":datetime.datetime.now().timestamp()}
        dataarr = []
        if int(self.size) > 0:
            address = commandarr[0]
            tempdata = tcpclient.runcommandfromui(("mrd %s %s" % (address, str(self.size))), "syswatch", self.socketdetails)
            addresslen = len(address.split("0x")[-1])
            for i in range(len(tempdata)):
                tempdata[i] = tempdata[i].split(":")
                if len(tempdata[i])>1:
                    while len(tempdata[i][0])<addresslen:
                        tempdata[i][0]= "0"+str(tempdata[i][0])
                    tempdata[i][0] = "0x"+tempdata[i][0]
                    tempdata[i] = tempdata[i][0]+":"+tempdata[i][1]
            dataarr = dataarr + tempdata
        else:
            for i in range(len(commandarr)):
                dataarr.append("%s:%s"%((commandarr[i]).lower(), tcpclient.getcommandresponse(("mrd %s\n" % commandarr[i]), "syswatch", self.socketdetails)))
        sysArr["data"].append({"address":commandarr,"value":dataarr})
        return sysArr