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

import copy
import time
import types
import json
import logging
import traceback
from datetime import datetime
from pony.orm import *
from model import fullStackDB
from model.login_logs import LoginLogs
from model.user import User
from utils import sql_filter

logger = logging.getLogger("LoginLogsManager")

class LoginLogsManager(object):
    def __init__(self):
        super(LoginLogsManager, self).__init__()

    def add(self, user, data):
        # 判断角色名是否存在
        result = LoginLogs.get(name=data.get("name"))
        if result:
            return False, "app logs name has been exists."

        editor = User.get(id=user)
        if not editor:
            return False, "current user is not exists"

        data.update({
            'create_by': editor,
            'create_at': datetime.now(),
        })

        result = fullStackDB.add(LoginLogs, **data)
        return result, "add app logs {}.".format("success" if result else "fail")

    def delete(self, user, uuid):
        with db_session:
            editor = User.get(id=user)
            if not editor:
                return False, "current user is not exists"

            result = LoginLogs.get(uuid=uuid)
            if result:
                result.delete()

            return result, "delete app logs {}.".format("success" if result else "fail")

    def get(self, data):
        result = LoginLogs.get(**data)
        if result:
            result = result.to_dict(with_collections=True, related_objects=True)
        return result, "get app logs {}.".format("success" if result else "fail")

    def getList(self, user, data):
        if not data or len(data) <= 0:
            return False, 0, "parameters can not be null"

        temp = copy.deepcopy(data)
        if 'pagenum' in temp:
            temp.pop('pagenum')
        if 'pagesize' in temp:
            temp.pop('pagesize')
        if 'scope_type' in temp:
            temp.pop('scope_type')

        with db_session:
            editor = User.get(id=user)
            if not editor:
                return False, "current user is not exists"
            temp.update({ 'create_by': editor })

            if "scope_type" in data and data.get("scope_type") == "list":
                result = LoginLogs.select().where(**temp).order_by(desc(LoginLogs.create_at))
                temp = []
                for item in result:
                    temp.append(item.to_dict(only=["uuid"]))
                return temp, len(temp), "get select {}.".format("success" if temp else "no data")

            result = LoginLogs.select().where(**temp).order_by(desc(LoginLogs.create_at)).page(data.get("pagenum", 1), data.get("pagesize", 10))
            count = LoginLogs.select().where(**temp).count()

        if result and len(result):
            temp = []
            for item in result:
                t = item.to_dict(with_collections=True, related_objects=True)
                t.update({
                    "create_at": item.create_at.strftime("%Y-%m-%d %H:%M:%S"),
                    "create_by": item.create_by.to_dict(only=["uuid", "username"]),
                })
                temp.append(t)
            result = temp

        return result, count, "get app logs {}.".format("success" if result else "no data")

    def update(self, user, uuid, data):
        # 当参数为空时，直接返回错误
        if len(data) <= 0 or (len(data.keys()) == 1 and "id" in data):
            return False, "parameters can not be null."

        # 查询请求者是否存在
        editor = User.get(id=user)
        if not editor:
            return False, "current user is not exists"

        return True, "update app logs {}.".format("success" if True else "fail")

loginLogsManager = LoginLogsManager()
