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

import copy
import time
import types
import json
import logging
import traceback
import urllib
from urllib import parse, request
from urllib.parse import urlparse, urljoin, urlencode
from datetime import datetime
from threading import Thread
from werkzeug.security import check_password_hash
from flask import request as flask_request
from pony.orm import *
from model import fullStackDB
from model.user import User
from model.login_logs import LoginLogs
from fullstack.login import Auth
from fullstack.response import ResponseCode
from utils import md5_salt, ThreadMaker

logger = logging.getLogger("LoginManager")

@ThreadMaker
def update_login_information(ip, user_id):
    params = { 'ak': 'aZEAgYG8wKuLd6DS9BmCloGtfnGGkRMn', 'coor': 'bd09ll' }
    parameters = urllib.parse.urlencode(params)
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko'
    }

    if ip != '127.0.0.1':
        params.update({'ip': ip})
        parameters = urllib.parse.urlencode(params)

    url = 'http://api.map.baidu.com/location/ip'
    req = request.Request(url='%s%s%s' % (url, '?', parameters), headers=headers)
    ret = request.urlopen(req).read()
    jsonData = json.loads(ret)
    logger.info(jsonData)

    if (0 != jsonData['status']):
        return None

    with db_session:
        user = User.get(id=user_id)
        if not user:
            return

        LoginLogs(username=user.username, ip=ip, address=jsonData['address'], create_by=user, remarks=json.dumps(jsonData['content'], ensure_ascii=False))
        commit()

class LoginManager(object):
    '''
     用户管理的单例类
    '''

    def __init__(self):
        super(LoginManager, self).__init__()
        # Thread(target=self.dashboard).start()

    def login(self, data):
        '''
        用户登录
        :param data:登录的用户信息json如 { "account": "xx", "password": "xx" }
        :return ret: dict类型的登录相关信息
        '''

        with db_session:
            # 判断用户名是否存在
            result = User.get(account=data.get("account"))
            if not result:
                return False, ResponseCode.NO_DATA_FOUND

            # 判断密码是否正确
            result = User.get(account=data.get("account"), password=md5_salt(data.get("password")))
            if not result:
                return False, ResponseCode.PASSWORD_ERROR

            # 判断用户是否禁用
            if result.is_delete:
                return False, ResponseCode.ACCOUNT_DISABLED

            real_ip = flask_request.headers['X-Forwarded-For']
            update_login_information(real_ip, result.id)

            # 返回token
            token = Auth.encode_auth_token(result.id, result.username) # 生成 token
            # setattr(result, 'token', token)
            return { 'token': token, 'id': result.id, 'username': result.username }, ResponseCode.OK

    def logout(self):
        '''
        用户登出
        '''
        return True, "user logout success."

    def register(self, data):
        '''
        用户注册
        '''
        with db_session:
            # 判断账号是否存在
            editor = User.get(account=data.get("account"))
            if editor:
                return False, "user already exists"

            data.update({
                "password": md5_salt(data['password']),
                "create_by": 0,
                "create_at": datetime.now(),
                "update_by": 0,
                "update_at": datetime.now()
            })

            result = User(**data)
            commit()
            result.create_by = result.id
            result.update_by = result.id
            commit()
            return result, "user register {}.".format("success" if result else "fail")

loginManager = LoginManager()
