import os
import sys
from edge_engine.common.constants import LicenseModule
from dateutil import parser
from datetime import datetime
from pymongo import MongoClient
from copy import deepcopy
import json
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 False
        return True
    except KeyError as e:
        sys.stderr.write("Error loading licence")
        return False


def get_config_from_mongo(mongo_uri, dbname, basecollection,
                          key, value):
    mongo = MongoClient(mongo_uri)

    db = mongo[dbname]
    config = db[basecollection].find_one({key: value}, {"_id": False})
    return config




def load_conf(config,mongo_uri, dbname):
    mongo = MongoClient(mongo_uri)
    db = mongo[dbname]
    pub_configs = []

    for conf in config['pubConfigs']:
        if conf["type"].lower() in ["mqtt","mongo",]:
            key= conf["key"]
            value=conf["value"]
            collection = conf["conectionCollection"]
            pub_conf = db[collection].find_one({key: value}, {"_id": False})
            pub_conf.update(conf)
            pub_configs.append(pub_conf)
        else :
            pub_configs.append(conf)

    config['pubConfigs'] = pub_configs

    return config



# """
# {
# "MONGO_URI": "mongodb://192.168.3.220:21017",
# "MONGO_DATABASE": "ilens_thermal_app",
# "MONGO_COLLECTION": "janus_deployment_details",
# "MONGO_KEY": "deploymentId",
# "MONGO_VALUE": "ddd"
# }
# """

LOG_LEVEL = os.environ.get("LOG_LEVEL", default="INFO").upper()
LOG_HANDLER_NAME = os.environ.get("LOG_HANDLER_NAME", default="ilens-edge_engine")

BASE_LOG_PATH = os.environ.get('BASE_LOG_PATH',
                               default=os.path.join(os.getcwd(), "logs".format()))

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

CONFIG_ENV  =  json.loads(os.environ.get('config', default=None))
sys.stdout.write("config->{} \n".format(json.dumps(CONFIG_ENV)))
MONGO_URI = CONFIG_ENV.get('MONGO_URI', None)
MONGO_DATABASE = CONFIG_ENV.get('MONGO_DATABASE', None)
MONGO_COLLECTION = CONFIG_ENV.get('MONGO_COLLECTION', None)
MONGO_KEY = CONFIG_ENV.get('MONGO_KEY', None)
MONGO_VALUE = CONFIG_ENV.get('MONGO_VALUE',None)

if MONGO_URI == None \
        or MONGO_DATABASE is None \
        or MONGO_COLLECTION is None \
        or MONGO_KEY is None \
        or MONGO_VALUE is None:
    sys.stderr.write("invalid mongo config  \n")
    sys.exit(1)

EDGE_CONFIG = get_config_from_mongo(
    mongo_uri=MONGO_URI,
    dbname=MONGO_DATABASE, basecollection=MONGO_COLLECTION,
    key=MONGO_KEY, value=MONGO_VALUE
)
DEVICE_ID =  EDGE_CONFIG["deviceId"]
if EDGE_CONFIG is None:
    sys.stderr.write("invalid EDGE_CONFIG config  \n")
    sys.exit(1)

EDGE_CONFIG=load_conf(EDGE_CONFIG, mongo_uri=MONGO_URI,
    dbname=MONGO_DATABASE)
DATA_PATH = EDGE_CONFIG["inputConf"].get('dataPath',os.path.join(os.getcwd(), "data".format()))

sys.stderr.write("Loading data from {} \n".format(DATA_PATH))