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

import json
from application.app import db, ma
from .base import PrimaryModel
from marshmallow import Schema, fields, INCLUDE, EXCLUDE
from webcreator.log import logger

class LoginModel(PrimaryModel):
    __tablename__ = 'evm_login'

    user = db.Column(db.Integer, nullable = False)
    login_at = db.Column(db.String(200), nullable = False)
    user_agent = db.Column(db.String(200), nullable = False)
    ip = db.Column(db.String(128), nullable = False)
    geo_location = db.Column(db.String(200), nullable = False)
    operator = db.Column(db.String(50), nullable = False)

    # __table_args__ = (
    #     db.Index('idx_xxx', 'xxx', mysql_using='btree'),
    # )

    def __init__(self, user, login_at, user_agent, ip, geo_location, operator):
        self.user = user
        self.login_at = login_at
        self.user_agent = user_agent
        self.ip = ip
        self.geo_location = geo_location
        self.operator = operator

    # def __getattr__(self, key):
    #     return self.__dict__[key]

    # def __getitem__(self, key):
    #     return self.get(key)

    # def __getattribute__(self, value):
    #     return value

    def __repr__(self):
        return '<LoginModel %r>' % (self.user)

    def to_dict(self):
        return {
            'login_at': self.login_at,
            'user_agent': self.user_agent,
            'ip': self.ip,
            'geo_location': self.geo_location,
            'operator': self.operator,
        }


class PostLoginSchema(ma.SQLAlchemySchema):
    class Meta:
        # unknown = INCLUDE # 未知字段默认包含
        unknown = EXCLUDE # 未知字段默认排除
        model = LoginModel

    account = fields.String(required=True, length=64)
    password = fields.String(required=True, length=64)

postLoginSchema = PostLoginSchema()

class GetListLoginSchema(ma.SQLAlchemySchema):
    class Meta:
        # unknown = INCLUDE # 未知字段默认包含
        unknown = EXCLUDE # 未知字段默认排除
        model = LoginModel

    page = fields.Integer(required=False)
    pageSize = fields.Integer(required=False)
    user = fields.Integer(required=False)
    login_at = fields.String(required=False)
    user_agent = fields.String(required=False)
    ip = fields.String(required=False)
    geo_location = fields.String(required=False)
    operator = fields.String(required=False)

getListLoginSchema = GetListLoginSchema()
getListLoginsSchema = GetListLoginSchema(many=True)

class GetLoginSchema(ma.SQLAlchemySchema):
    class Meta:
        # unknown = INCLUDE # 未知字段默认包含
        unknown = EXCLUDE # 未知字段默认排除
        model = LoginModel

    user = fields.Integer(required=False)
    login_at = fields.String(required=False)
    user_agent = fields.String(required=False)
    ip = fields.String(required=False)
    geo_location = fields.String(required=False)
    operator = fields.String(required=False)

getLoginSchema = GetLoginSchema()
