#!/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 flask import request
from model import fullStackDB
from model.depot import Depot
from model.role import Role
from model.user import User
from utils import sql_filter

logger = logging.getLogger("RoleManager")

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

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

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

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

        result = fullStackDB.add(Role, **data)
        return result, "add role {}.".format("success" if result else "fail")

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

        result = fullStackDB.update(Role, { 'uuid': uuid }, is_delete=True, delete_at=datetime.now(), delete_by=editor)
        return result, "delete role {}.".format("success" if result else "fail")

    def get(self, data):
        result = Role.get(**data)
        if result:
            result = result.to_dict(with_collections=True, related_objects=True, only=["uuid", "name", "create_at", "update_at", "delete_at"])
        return result, "get role {}.".format("success" if result else "fail")

    def getList(self, 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')
        temp.setdefault("is_delete", False)

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

        result = fullStackDB.pagination(Role, Role.create_at, pagenum=data.get("pagenum", 1), pagesize=data.get("pagesize", 10), **temp)
        count = fullStackDB.count(Role, **temp)

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

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

    def update(self, 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=request.current_user.get("id"))
        if not editor:
            return False, "current user is not exists"

        result = None
        with db_session:
            result = Role.get(uuid=uuid)
            if result:
                result.set(update_at=datetime.now(), update_by=editor, **data)
                commit()
        # result = fullStackDB.update(Role, { 'uuid': uuid }, update_at=datetime.now(), update_by=editor, **data)
        return result, "update role {}.".format("success" if result else "fail")

roleManager = RoleManager()
