import base64
import configparser
import json

import jwt
import os
import sys
# import paho.mqtt.client as mqtt
from pymongo import MongoClient
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"))

MAIN_OS_VARIABLE = json.loads(os.environ.get('config'))
if MAIN_OS_VARIABLE is None:
    sys.stderr.write("Configuration not found...")
    sys.stderr.write("Exiting....")
    sys.exit(1)

MONGO_URI = MAIN_OS_VARIABLE.get('MONGO_URI')
MONGO_SERVICE_DB = MAIN_OS_VARIABLE.get('MONGO_DB')
# MONGO_SERVICE_COLL = MAIN_OS_VARIABLE.get('MONGO_COLL')
# PASS_KEY = MAIN_OS_VARIABLE.get('PASS_KEY')
EMAIL_ID = MAIN_OS_VARIABLE.get('EMAIL_ID')
EMAIL_PASSWORD = MAIN_OS_VARIABLE.get('EMAIL_PASSWORD')

x = MONGO_URI.split('@')
y = x[1].split(':')
mongo_host = x[0] + '@' + y[0]
mongo_port = y[1]
# 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=" ")

# MONGO_DB_OBJ = MongoClient(MONGO_URI)[MONGO_SERVICE_DB]

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=" ")


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

