from django.views import View
from django.http import HttpResponse
from bson.json_util import dumps,loads
from .settings import *
import re
import uuid
import random
from datetime import datetime
import string
from .models import *
import random 
#import string

def getHeaders(request):
    regex = re.compile('^HTTP_')
    headers = dict((regex.sub('', header), value) for (header, value) in request.META.items() if header.startswith('HTTP_'))
    return headers

def requestId():
   # random = ''.join([random.choice(string.ascii_letters + string.digits) for n in range(7)])
    return ''.join([random.choice(string.ascii_letters + string.digits) for n in range(7)])

def generateUserToken():
    # get a random UUID 
    token = str(uuid.uuid4()).replace('-', '')  # generate Uid
    return token

def getRecordId():
	return ''.join([random.choice(string.digits) for n in range(6)])

def verifyUserToken1(userToken):
    userRoleCheck = loads(dumps(db.users.find_one({"userToken":{'$in':[userToken]}}, {'_id': 0,'userId':1, 'userName': 1,'password':1,'userToken':1,'role':1}))) # check the token in db
    result = {'message': 'Unauthorized User.', 'status': 'failed'}
    if userRoleCheck:  # if token find
        result.update({
        'message': 
        'user authorized', 
        'status':'success', 
        'userId': userRoleCheck['userId'],
        'userName':userRoleCheck['userName'],'password':userRoleCheck['password'],'userToken':userRoleCheck['userToken'],'role':userRoleCheck['role']}) # return response with role,userId and user name
    return result    
#************** This Function is used to maintain log records **************#
# def logFiles(userId,eventType,userName,time,method,description,response):
#     if userId!='' and response['status']=='success': # if userId given
#         fd = open(os.path.join(LogFile_PATH,userId+'.txt'), "a") # open file with userId as file name
#         fileData=eventType+" "+timeStamp()
#         fd.write("\n"+fileData) # write data into the file
#         fd.close() # close the file
#         db.dashboard.insert({"userId":userId,"userName":userName,"time":time,"eventType":eventType,"method":method,"description":description}) # save the log record in db
#     else: # if un authorized user
#         print('falseee')
#         event='Not A Valid User'
#         fd = open(os.path.join(LogFile_PATH,'General.txt'),'a') # open file with name as genereal.txt
#         fileData=event+' '+eventType+" "+timeStamp()
#         fd.write("\n"+fileData) # write the data into file
#         fd.close() # close file
#         return True

def passwordValidator(password):
    flag = 0
    while True: 
        if  (len(password)>12) or (len(password)<8): # check the length of password
            flag = -1
            break
        elif not re.search("[a-z]", password): # check password contains alphabets(lower case)
            flag = -1
            break
        elif not re.search("[A-Z]", password): #check password contains alphabets(upper case)
            flag = -1
            break
        elif not re.search("[0-9]", password): #check password contains numeric
            flag = -1
            break
        elif not re.search("[_@$]", password): #check password contains special characters
            flag = -1
            break
        #elif re.search("\s", password): 
            #flag = -1
            #break
        else: 
            flag = 0
            pswCheck=True
            break
    if flag ==-1: 
        pswCheck=False
    return pswCheck # return password        


def emailValidator(mailId):
    splittedMailId=mailId.split('@') # split the given email Id before and after @
    flag = 0
    while True:
        if not re.match('^[a-zA-Z0-9._-]{2,20}$',splittedMailId[0]): # match the mail with regex
            flag=1
            break
        if not re.match('^[a-zA-Z0-9-]+\\.[a-zA-Z]{2,6}$',splittedMailId[1]):
            flag=1
            break
        else:
            flag=0
            emailCheck=True # if matched return message True or false
            break
    if flag==1:
        emailCheck=False
    return emailCheck  