# -*- coding: utf-8 -*-

import json
import hashlib
import psycopg2

from tornado import gen

from .main_handlers import BaseHandler


class AuthCreateUserHandler(BaseHandler):
    # FIX ME
    def post(self):
        pass


class AuthLoginHandler(BaseHandler):
    def get(self):
        self.redirect('/')

    def password_is_correct(self, password_got, expected):
        password_got = hashlib.md5(password_got).hexdigest()
        return password_got == expected

    @gen.coroutine
    def post(self):
        email = self.get_argument("email")
        password = self.get_argument("password")
        query = "SELECT * FROM users WHERE email = '%s'" % email
        cur = yield self.db.execute(query)
        try:
            user = cur.fetchone()
            user_password = user[3]
        except (psycopg2.ProgrammingError, TypeError):
            user = None
            user_password = None
        if not user or not self.password_is_correct(password, user_password):
            self.set_status(403)
            self.write(json.dumps({"status": "Forbidden"}))
            return
        user_id = str(user[0])
        self.set_secure_cookie("user", user_id)
        self.set_status(200)
        self.write(json.dumps({"status": "OK"}))


class AuthLogoutHandler(BaseHandler):
    @gen.coroutine
    def get(self):
        self.clear_cookie("user")
        self.set_status(200)
        data = json.dumps({'status': "OK"})
        self.write(data)
