##
# 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="",hw_name="",module_name="",register_name="",bit_field="",address="",legend="",displayname="",y_axis="",client="",active_client=""):
        self.threadname = threadname
        self.hw_name = hw_name
        self.module_name = module_name
        self.register_name = register_name
        self.bit_field = bit_field
        self.address = address
        self.legend = legend
        self.y_axis = y_axis
        self.plotthread = ""
        self.displayname = displayname
        self.client = client
        self.plotstatus = True
        self.active_client = active_client
        self.thread_createtime = datetime.datetime.now().timestamp()

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

    def newconnection(self):
        # global connection, channel
        mongoClient = MongoClient(settings.MONGO_URI)
        try:
            user = users.get_user(self.active_client, "connectionstatus")
            while user["connectionstatus"] and self.plotstatus:
                user = users.get_user(self.active_client, "connectionstatus")
                message = self.getlpdcounters(self.threadname)
                receiver.dbdump(mongoClient,self.active_client, message)           
            print("closing channel")
        finally:
            mongoClient.close()
        return 1

    def getlpdcounters(self,exchange):
        counterArr = {"tabname": "plot_"+self.active_client,"threadname":self.threadname,"y_axis":self.y_axis, "data": [],"thread_createtime":self.thread_createtime}
        counterData = {}
        newobj = {}
        counterData["data"] = []
        timenow = datetime.datetime.now().timestamp()
        counterArr["time"] = timenow

        status = False
        for i in range(len(counterArr["data"])):
            if counterArr["data"][i]["displayname"] == self.displayname:
                status = True
                tempvar = tcpclient.getcommandresponse(
                    ("mrd %s\n" % self.address), "plot",self.client)
                if all(c in 'xX' + string.hexdigits for c in tempvar):
                    counterArr["data"][i]["data"][0][self.legend] = str(
                        "%x" % (int(tempvar, 16)))
                else:
                    counterArr["error"] = "Error on reading data from board"
                break
            else:
                status = False

        if not status:
            obj = {}
            obj["data"] = []
            obj["displayname"] = self.displayname
            obj["key"] = self.threadname
            tempvar = tcpclient.getcommandresponse(("mrd %s\n" % self.address), "plot",self.client)
            if all(c in 'xX' + string.hexdigits for c in tempvar):
                obj["data"].append({"time": timenow, self.legend: str("%x" % (int(tempvar, 16)))})
                counterArr["data"].append(obj)
            else:
                counterArr["error"] = "Error on reading data from board"
        return counterArr