import os
import sys
from dateutil import parser
from datetime import datetime
import json
import requests


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


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))
print(CONFIG_ENV)
DEPLOYMENT_ID = CONFIG_ENV.get('DEPLOYMENT_ID',None)
print(DEPLOYMENT_ID)
GET_JANUS_DETAILS = CONFIG_ENV.get('GET_JANUS_DETAILS',None)
MONGO_URI_ADD_EVENTLOGS = CONFIG_ENV.get('MONGO_URI',None)
url = GET_JANUS_DETAILS + DEPLOYMENT_ID
EDGE_CONFIG = requests.get(url).json()["data"]
LAST_COUNT = requests.get(url).json()["cement_bag_count"]
if not LAST_COUNT:
    LAST_COUNT = 0
DEVICE_ID = EDGE_CONFIG["deviceId"]
DATA_PATH = EDGE_CONFIG["inputConf"].get('dataPath',os.path.join(os.getcwd(), "data".format()))

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