import base64
import configparser
import jwt
import os
import sys
# import paho.mqtt.client as mqtt

from datetime import datetime
from dateutil import parser
from scripts.common.constants import LicenseModule


def licence_validator(payload):
    try:
        dt = parser.parse(payload['valid_till'])
        now = datetime.now()
        if now > dt:
            sys.stdout.write("Licence Expired \n".format())
            sys.stdout.flush()
            return True
        return True
    except KeyError as err:
        sys.stdout.write(err)
        sys.stderr.write("Error loading licence")
        return True


CONFIGURATION_FILE = os.environ.get("CONF_PATH", os.path.join(os.getcwd(), "conf{0}settings.conf".format(os.sep)))
sys.stdout.write("Reading Config from  {} \n".format(CONFIGURATION_FILE))
sys.stdout.flush()
__config = configparser.ConfigParser()
__config.read(CONFIGURATION_FILE)

BASE_LOG_PATH = os.environ.get('BASE_LOG_PATH',
                               __config.get('LOGGER', 'basepath', fallback=os.path.join(os.getcwd(), "logs".format())))

if not os.path.isdir(BASE_LOG_PATH):
    os.mkdir(BASE_LOG_PATH)

DATA_PATH = os.environ.get('BASE_DATA_PATH', __config.get('CLIENT-CONFIG', 'basepath', fallback=os.path.normpath(
    os.getcwd() + '{}data'.format(os.sep))))
sys.stdout.write("Data base path  {} \n".format(DATA_PATH))

LICENCE_FILE = os.environ.get("LICENCE_FILE", __config.get('CLIENT-CONFIG', 'licence-life', fallback="license.lic"))
LICENCE_FILE = os.path.join(DATA_PATH, LICENCE_FILE)

sys.stdout.write("Loading Licence   {} \n".format(LICENCE_FILE))
try:
    private_key = LicenseModule.private_key
    encoding_algorithm = LicenseModule.encoding_algorithm
    LICENCE_PAYLOAD = jwt.decode(bytes(base64.b64decode(open(LICENCE_FILE, 'rb').read())), private_key,
                                 algorithms=[encoding_algorithm])
except Exception as e:
    sys.stderr.write("{}".format(e))
    sys.stderr.write(" **Error loading licence** \n")

LOG_LEVEL = os.environ.get("LOG_LEVEL", __config.get('LOGGER', 'loglevel', fallback="DEBUG")).upper()
LOGSTASH_HOST = os.environ.get("LOGSTASH_HOST", __config.get('LOGGER', 'loglevel', fallback=None))
LOGSTASH_PORT = os.environ.get("LOGSTASH_PORT", __config.get('LOGGER', 'loglevel', fallback=None))
LOG_HANDLER_NAME = os.environ.get("LOG_HANDLER_NAME", __config.get('LOGGER', 'loglevel', fallback="face-id"))

ATTENDANCE_MONGO_HOST = __config.get('ATTENDANCE MONGO', 'HOST', fallback="0.0.0.0")
ATTENDANCE_MONGO_PORT = int(__config.get('ATTENDANCE MONGO', 'PORT', fallback="27017"))
ATTENDANCE_MONGO_DATABASE = __config.get('ATTENDANCE MONGO', 'DATABASE', fallback=" ")
ATTENDANCE_MONGO_AUTH = __config.get('ATTENDANCE MONGO', 'AUTH', fallback="false")
ATTENDANCE_MONGO_USERNAME = __config.get('ATTENDANCE MONGO', 'USERNAME', fallback=" ")
ATTENDANCE_MONGO_PASSWORD = __config.get('ATTENDANCE MONGO', 'PASSWORD', fallback=" ")
ATTENDANCE_MONGO_INVOICES_COLLECTION = __config.get('ATTENDANCE MONGO', 'INVOICE_COLLECTION', fallback=" ")
ATTENDANCE_MONGO_REGISTER_COLLECTION = __config.get('ATTENDANCE MONGO', 'REGISTER_COLLECTION', fallback=" ")
KL_BOT_JOB_COLLECTION = __config.get('ATTENDANCE MONGO', 'JOB_COLLECTION', fallback=" ")
ATTENDANCE_MONGO_MODEL_COLLECTION = __config.get('ATTENDANCE MONGO', 'MODEL_COLLECTION', fallback=" ")
KL_BOT_MONGO_COLLECTION = __config.get('ATTENDANCE MONGO', 'BOT_COLLECTION', fallback=" ")
# ATTENDANCE_MONGO_CAMERA_COLLECTION = __config.get('ATTENDANCE MONGO', 'CAMERA_COLLECTION', fallback=" ")
# ATTENDANCE_MONGO_EVENT_COLLECTION = __config.get('ATTENDANCE MONGO', 'EVENTS_COLLECTION', fallback=" ")
# ATTENDANCE_MONGO_SERVICE_COLLECTION = __config.get('ATTENDANCE MONGO', 'SERVICE_COLLECTION', fallback=" ")
# ATTENDANCE_MONGO_SITE_COLLECTION = __config.get('ATTENDANCE MONGO', 'SITE_COLLECTION', fallback=" ")
# ATTENDANCE_MONGO_THRESHOLD_COLLECTION = __config.get('ATTENDANCE MONGO', 'THRESHOLD_COLLECTION', fallback=" ")
# ATTENDANCE_MONGO_TAG_COLLECTION = __config.get('ATTENDANCE MONGO', 'TAG_COLLECTION', fallback=" ")
# ALARM_COLLECTION = __config.get('ATTENDANCE MONGO', 'ALARM_COLLECTION', fallback=" ")
# ALARM_PRIORITY_TYPE_COLLECTION = __config.get('ATTENDANCE MONGO', 'ALARM_PRIORITY_TYPE_COLLECTION', fallback=" ")
# STATIC_CONTENT_COLLECTION = __config.get('ATTENDANCE MONGO', 'STATIC_CONTENT_COLLECTION', fallback=" ")
# WORK_GROUP_COLLECTION = __config.get('ATTENDANCE MONGO', 'WORK_GROUP_COLLECTION', fallback=" ")
# USER_COLLECTION = __config.get('ATTENDANCE MONGO', 'USER_COLLECTION', fallback=" ")
# NOTIFICATIONS_COLLECTION = __config.get('ATTENDANCE MONGO', 'NOTIFICATIONS_COLLECTION', fallback=" ")
# AI_MODEL_COLLECTION = __config.get('ATTENDANCE MONGO', 'AI_MODEL_COLLECTION', fallback=" ")
# DEVICE_DATABASE = __config.get('ATTENDANCE MONGO', 'DEVICE_DATABASE', fallback=" ")
# DEVICE_COLLECTION = __config.get('ATTENDANCE MONGO', 'DEVICE_COLLECTION', fallback=" ")
# JANUS_DEPLOYMENT_COLLECTION = __config.get('ATTENDANCE MONGO', 'JANUS_DEPLOYMENT_COLLECTION', fallback=" ")
# CONTAINER_DEPLOYMENT_COLLECTION = __config.get('ATTENDANCE MONGO', 'CONTAINER_DEPLOYMENT_COLLECTION', fallback=" ")

SERVICE_HOST = __config.get('SERVICE', 'HOST', fallback="0.0.0.0")
SERVICE_PORT = int(__config.get('SERVICE', 'PORT', fallback="5000"))

# DEVICE = __config.get('ILENS DEVICE', 'DEVICE', fallback="")
# TAG = __config.get('ILENS DEVICE', 'TAG', fallback="")
#
# MODELSERVER_HOST = __config.get('MODELSERVER', 'HOST', fallback="")
# MODELSERVER_PORT = int(__config.get('MODELSERVER', 'PORT', fallback=""))
# MODELSERVER_TRAIN_EP = __config.get('MODELSERVER', 'TRAIN_EP', fallback="")


# IMAGE_DIRECTORY_BASEPATH = __config.get('TRAIN_USERS', 'DIRECTORY_BASEPATH', fallback="")
# ALLOWED_EXTENSIONS = {'png', 'jpeg', 'jpg'}
# MQTT_HOST = __config.get('RECORDINGS', 'MQTT_HOST', fallback="192.168.207")
# MQTT_PORT = int(__config.get('RECORDINGS', 'MQTT_PORT', fallback="31250"))
# MQTT_TOPIC = __config.get('RECORDINGS', 'MQTT_TOPIC', fallback="video_recording")

# THERMAL_ATTENDANCE_MONGO_HOST = __config.get('NEW ATTENDANCE', 'HOST', fallback="0.0.0.0")
# THERMAL_ATTENDANCE_MONGO_PORT = int(__config.get('NEW ATTENDANCE', 'PORT', fallback="27017"))
# THERMAL_ATTENDANCE_MONGO_DATABASE = __config.get('NEW ATTENDANCE', 'DATABASE', fallback=" ")
# THERMAL_ATTENDANCE_MONGO_AUTH = __config.get('NEW ATTENDANCE', 'AUTH', fallback="false")
# THERMAL_ATTENDANCE_MONGO_USERNAME = __config.get('NEW ATTENDANCE', 'USERNAME', fallback=" ")
# THERMAL_ATTENDANCE_MONGO_PASSWORD = __config.get('NEW ATTENDANCE', 'PASSWORD', fallback=" ")
# THERMAL_ATTENDANCE_MONGO_EVENT_COLLECTION = __config.get('NEW ATTENDANCE', 'THERMAL_COLLECTION', fallback=" ")
#
# JS_HOST = __config.get('JANUS_SERVER', 'HOST', fallback=" ")
# JS_PORT = int(__config.get('JANUS_SERVER', 'PORT', fallback=" "))
# JS_EP = __config.get('JANUS_SERVER', 'JANUS_EP', fallback=" ")
#
# MINIO_SECRET_KEY = __config.get('MINIO', 'SECRET_KEY', fallback=" ")
# MINIO_ACCESS_KEY = __config.get('MINIO', 'ACCESS_KEY', fallback=" ")
# MINIO_BUCKET_NAME = __config.get('MINIO', 'BUCKET_NAME', fallback=" ")
# MINIO_IP = __config.get('MINIO', 'MINIO_IP', fallback=" ")
# MINIO_LOCAL_DATA_PATH = __config.get('MINIO', 'LOCAL_DATA_PATH', fallback=" ")
