import logging
logging.basicConfig()
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
logger.info("Loaded " + __name__)

import cv2
import requests
from base64 import b64encode, b64decode
import json
import time
import numpy as np

class detectorClient():
    
    def __init__(self,config={}):
        
        logger.info("initialized with config -{}".format(config))
        endpoint=config.get("endpoint","http://localhost")
        port=config.get("port",8000)
        route=config.get("route",'detect')
        maxFailedAttempts=config.get("maxFailedAttempts",5000)
        
        self.url="{}:{}/{}".format(endpoint,port,route)
        self.headers = {'Content-Type': 'application/json'}
        self.failedAttempts=0
        self.maxFailedAttempts=maxFailedAttempts
        
    def detect(self,image,**kwargs):
        try:
            threshold=kwargs.get("threshold",0.5)
            encoded= b64encode(cv2.imencode('.jpg', image)[1]).decode('utf-8')
            data={"image":encoded,"threshold":threshold}
            response = requests.request("POST", self.url, data=json.dumps(data), headers=self.headers,timeout=10)
            response.raise_for_status()
            dets= response.json()["detections"]
            return dets
        
        except Exception as e:
            message=""
            self.failedAttempts += 1
            if self.failedAttempts > self.maxFailedAttempts:
                raise Exception("detection server not accessible!")
            try:
                resp=response.json()
                message=resp["message"]
            except:
                pass
       
            logger.info("Error in detection call-{},message-{}".format(str(e),message))
            return []
        
        
        
if __name__ == '__main__':
    detector=detectorClient({})
    while True:
        img=np.random.rand(300,300,3)
        det= detector.detect(img)
        print("dets",det)