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

logger = logging.getLogger("DeviceManager")

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

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

            device = Device.select().where(imei=data.get("imei")).first()
            if device:
                return False, "device has been exists"

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

            result = Device(**data)
            commit()

            return result, "add Device {}.".format("success" if result else "fail")

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

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

    def get(self, user, data):
        result = Device.get(**data)
        if result:
            result = result.to_dict(with_collections=True, related_objects=True, only=["uuid", "create_at", "update_at", "delete_at"])
        return result, "get Device {}.".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"

            if editor.role == "administrator":
                temp.update({ "is_delete": False })
            else:
                temp.update({"create_by": editor, "is_delete": False})

            if "scope_type" in data and data.get("scope_type") == "list":
                result = Device.select().where(**temp).order_by(desc(Device.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 = Device.select().where(**temp).order_by(desc(Device.create_at)).page(data.get("pagenum", 1), data.get("pagesize", 10))
            count = Device.select().where(**temp).count()

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

            return result, count, "get Device {}.".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."

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

            if data.get("imei"):
                device = Device.select().where(imei=data.get("imei")).first()
                if device:
                    return False, "device has been exists"

            result = Device.get(uuid=uuid)
            if result:
                result.set(update_at=datetime.now(), update_by=editor, **data)
                commit()

            return result, "update role {}.".format("success" if result else "fail")

deviceManager = DeviceManager()
