#!/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.menu import Menu
from model.user import User
from utils import sql_filter

logger = logging.getLogger("MenuManager")

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

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

        result = Menu.get(path=data.get("path"))
        if result:
            return False, "menu path has been exists."

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

        result = fullStackDB.add(Menu, **data)
        return result, "add menu {}.".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(Menu, { 'uuid': uuid }, is_delete=True, delete_at=datetime.now(), delete_by=editor)
        return result, "delete menu {}.".format("success" if result else "fail")

    def get(self, data):
        result = Menu.get(**data)
        if result:
            result = result.to_dict(only=["uuid", "name", "create_at", "update_at"])
        return result, "get menu {}.".format("success" if result else "no data")

    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')
        if 'props' in temp:
            temp.pop('props')
        temp.setdefault("is_delete", False)

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

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

        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") })
                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 menu {}.".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 = fullStackDB.update(Menu, { 'uuid': uuid }, update_at=datetime.now(), update_by=editor, **data)
        return result, "update menu {}.".format("success" if result else "fail")

menuManager = MenuManager()
