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

import os
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.netdisc import Netdisc
from model.user import User
from app.setting import config

logger = logging.getLogger("NetDiscManager")

class NetDiscManager(object):
    def __init__(self):
        super(NetDiscManager, 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"

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

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

    def delete(self, data):
        # 通过uuid查询出所有的文件列表，然后全部删除
        editor = User.get(id=request.current_user.get("id"))
        if not editor:
            return False, "current user is not exists"

        count = 0
        result = []
        with db_session:
            for uuid in data.get("uuids"):
                nd = Netdisc.get(uuid=uuid)
                if nd:
                    # nd.is_delete = True
                    # nd.delete_at = datetime.now()
                    # nd.delete_by = editor
                    nd.set(is_delete = True, delete_at = datetime.now(), delete_by = editor)
                    count = count + 1
                    result.append([nd.is_dir, nd.real_path])
                    commit()

        return result, "delete {} netdisc {}.".format(count, "success" if result else "fail")

    def get(self, data):
        result = Netdisc.get(**data)
        if result:
            result = result.to_dict(only=["uuid", "name", "real_path"])
        return result, "get netdisc {}.".format("success" if result else "no data")

    def getList(self, data):
        data.update({ "is_delete": False })

        count = 0
        result = []
        with db_session:
            editor = User.get(id=request.current_user.get("id"))
            if not editor:
                return False, "current user is not exists"

            if editor.role.name != "超级管理员":
                data.update({ "create_by": editor })

            result = Netdisc.select().where(**data).order_by(Netdisc.name)
            count = len(result)

            files = []
            folders = []
            for item in result:
                t = item.to_dict(with_collections=True, related_objects=True, only=["uuid", "name", "size", "is_dir", "parent_dir", "file_type", "create_at", "update_at"])
                if item.is_dir:
                    t.update({
                        "is_dir": 1 if item.is_dir else 0,
                        "real_path": os.path.relpath(item.real_path, config.get("UPLOAD_PATH")).replace('\\', '/'),
                        "create_by": item.create_by.to_dict(only=["uuid", "username"]),
                        "update_by": item.update_by.to_dict(only=["uuid", "username"]),
                        "create_at": item.create_at.strftime("%Y-%m-%d %H:%M:%S"),
                        "update_at": item.update_at.strftime("%Y-%m-%d %H:%M:%S")
                    })
                    folders.append(t)
                else:
                    t.update({
                        "is_dir": 1 if item.is_dir else 0,
                        "real_path": os.path.relpath(item.real_path, config.get("UPLOAD_PATH")).replace('\\', '/'),
                        "create_by": item.create_by.to_dict(only=["uuid", "username"]),
                        "update_by": item.update_by.to_dict(only=["uuid", "username"]),
                        "create_at": item.create_at.strftime("%Y-%m-%d %H:%M:%S"),
                        "update_at": item.update_at.strftime("%Y-%m-%d %H:%M:%S")
                    })
                    files.append(t)

            result = folders + files

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

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

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

                _ext = os.path.splitext(result.real_path)[-1]
                _dir = os.path.dirname(result.real_path)

                filename = data.get("name") + _ext
                data.update({ "real_path": os.path.normpath(os.sep.join([_dir, filename])) })
                result = { "src": _real, "dst": data.get("real_path") }

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

netDiscManager = NetDiscManager()
