from model import default
import json
import hashlib
from datetime import datetime
from flask import request
from config import CONFIG

from model import token

class model(default.model):
	def __init__(self, connection):
		self.connection = connection
		self.objName = 'USERS'
		self.token = token.model(self.connection)

	def encodePassword(self, password):
		return hashlib.md5(password.encode()).hexdigest()

	def create(self, data = None ):
		data['password'] = self.encodePassword(data['password'])

		cursor = self.connection.cursor()
		cursor.execute('SELECT * FROM {0} WHERE(login="{1}" AND password="{2}");'.format(self.objName, data['login'], data['password']))
		rows = cursor.fetchall()
		if (len(rows) == 1):
			devid = hashlib.md5((data['sessionid'] + request.headers.get('User-Agent') + CONFIG['md5_salt']).encode()).hexdigest()
			now = datetime.now()
			timestamp = round(datetime.timestamp(now)) + 600
			token =  hashlib.md5((devid + str(timestamp)).encode() ).hexdigest()
			token_data = {'token': token, 'devid': devid, 'login': data['login'], 'expire': timestamp}
			self.token.create(token_data)
			return {'token': token}
		else:
			return {'errors': ['Bad login or password!']}

	def read(self):
		return {}

	def update(self, id, data):
		return {}

	def delete(self, id):
		return self.token.deleteToken(id)

	def deleteAll(self, id):
		return self.token.deleteAllUserToken(id)
