from model import default
import hashlib
from datetime import datetime

from config import CONFIG

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

	def check(self, request):
		cursor = self.connection.cursor()

		devid = hashlib.md5((request.headers.get('sessionid')+request.headers.get('User-Agent')+CONFIG['md5_salt']).encode()).hexdigest()
		now = datetime.now()
		timestamp = round(datetime.timestamp(now))

		# delete old tokens
		try:
			SQL = 'DELETE FROM {0} WHERE (expire<{1})'.format(self.objName, timestamp)
			cursor.execute(SQL)
			self.connection.commit()
		except Exception:
			print (Exception)

		SQL = 'SELECT * FROM {0} WHERE(token="{1}" AND devid="{2}" AND expire>{3});'.format(self.objName, request.headers.get('token'), devid, timestamp)
		cursor.execute(SQL)
		rows = cursor.fetchall()

		if (len(rows) > 0):
			# Update Token expire date
			try:
				SQL = 'UPDATE {0} SET expire={1} WHERE(id={2});'.format(self.objName, timestamp + 600, rows[0][0])
				cursor.execute(SQL)
				self.connection.commit()
			except Exception:
				print (Exception)			

			return True
		else:
			return False

	def deleteToken(self, token):
		cursor = self.connection.cursor()
		# delete tokens
		try:
			SQL = 'DELETE FROM {0} WHERE (token="{1}")'.format(self.objName, token)
			cursor.execute(SQL)
			self.connection.commit()
		except Exception:
			print (Exception)
		return {'result':'OK'}
		
	def deleteAllUserToken(self, token):
		cursor = self.connection.cursor()
		SQL = 'SELECT login FROM {0} WHERE(token="{1}");'.format(self.objName, token)
		cursor.execute(SQL)
		rows = cursor.fetchall()
		if (len(rows) > 0):
			try:
				user = rows[0][0] 
				SQL = 'DELETE FROM {0} WHERE(login="{1}");'.format(self.objName, user)
				cursor.execute(SQL)
				self.connection.commit()
			except Exception:
				print (Exception)
		return {'result':'OK'}
