#!/usr/bin/env python
# -*- coding: utf_8 -*-

import json
import pprint
from datetime import datetime
from flask_jwt_extended import (create_access_token,)
from application.app import db
from models.login import LoginModel
from models.user import UserModel
from webcreator.log import logger
from webcreator import utils
from webcreator.response import ResponseCode

@utils.ThreadMaker
def update_login_information(ip, log_id):
    try:
        jsonData = utils.get_location_by_ip(ip)
        if (0 != jsonData['status']):
            return None

        record = LoginModel.query.filter(LoginModel.id==log_id).first()
        record.geo_location = json.dumps(jsonData, ensure_ascii=False)
        db.session.commit()
    except Exception as e:
        logger.error(e)

class LoginResource(object):
    def __init__(self):
        super().__init__()

    def get(self, uuid, params):
        # handle business
        filters = [LoginModel.is_delete==False, LoginModel.uuid==uuid]
        result = LoginModel.query.filter(*filters).first()
        if result:
            return result, ResponseCode.HTTP_SUCCESS
        return None, ResponseCode.HTTP_NOT_FOUND

    def getList(self, params):
        # handle business
        logger.warn(params)
        filters = [LoginModel.is_delete==False]
        result = LoginModel.query.filter(*filters).order_by(LoginModel.create_at).paginate(params.get('page', 1), params.get('pageSize', 10), error_out=False)

        if result:
            return result, ResponseCode.HTTP_SUCCESS
        return None, ResponseCode.HTTP_NOT_FOUND

    def post(self, params, jwt={}):
        # handle business
        user = UserModel.query.filter(UserModel.account==params.get("account")).first()
        if not user:
            return False, ResponseCode.USER_NOT_EXISTS

        logger.info(params)
        if user.password != utils.md5_encryption(params.get("password")):
            return False, ResponseCode.USER_PASSWORD_ERROR

        # 插入一条登录记录
        obj = { 'user': user.id, 'user_agent': params.get("user_agent"), 'ip': params.get("ip"), 'geo_location': '', 'operator': '', 'login_at': datetime.now().strftime("%Y-%m-%d %H:%M:%S")  }
        result = LoginModel(**obj)
        result.operator = ""
        db.session.add(result)
        db.session.commit()

        # 获取当前登录IP地理位置信息
        update_login_information(params.get("ip"), result.id)

        # 生成一个token，返回给前端
        result = {
            'uuid': str(user.uuid),
            'name': user.username,
            'token': create_access_token(identity={'uuid': str(user.uuid), 'name': user.username}),
        }
        pprint.pprint(result)
        return result, ResponseCode.HTTP_SUCCESS

    def put(self, uuid, params, jwt={}):
        # handle business
        result = LoginModel.query.filter(LoginModel.uuid==uuid).first()
        if not result:
            return None, ResponseCode.HTTP_NOT_FOUND

        if params:
            for key, value in params.items():
                if value != None: setattr(result, key, value)
            result.update_by = jwt.get("id", "")
            result.update_date = datetime.now()
            db.session.commit()
            return True, ResponseCode.HTTP_SUCCESS
        else:
            return False, ResponseCode.HTTP_INVAILD_REQUEST

    def delete(self, uuid, jwt={}):
        # handle business
        result = LoginModel.query.filter(LoginModel.uuid==uuid).first()
        if not result:
            return False, ResponseCode.HTTP_NOT_FOUND

        result.update_by = jwt.get("id", "")
        result.update_date = datetime.now()
        result.is_delete = True
        db.session.delete(result)
        db.session.commit()
        return True, ResponseCode.HTTP_SUCCESS

loginManager = LoginResource()
