'''
Author: your name
Date: 2021-06-21 14:52:24
LastEditTime: 2021-06-30 12:27:59
LastEditors: Please set LastEditors
Description: In User Settings Edit
FilePath: \evm-store\tools\modules\file-manager\main.py
'''

import os
import shutil
import pprint
from pathlib import Path, PurePosixPath, PureWindowsPath
import platform
import json
from fs.osfs import OSFS
from fs import open_fs
from fs.walk import Walker

disk_root = "D:\\projects\\scriptiot\\evm_app_store_files"

class FileManager(object):
    def __init__(self) -> None:
        pass

    '''
    @description: 根据前端传递的路径参数，获取该路径的目录以及文件信息，文件类别，可以看做是一个盘符
    @param {*} self
    @return {*}
    '''
    def initialize(self):
        '''
        disks: {
            files: {driver: "local"},
            images: {driver: "local"}
        }
        lang: "en"
        leftDisk: null
        rightDisk: null
        windowsConfig: 2
        '''

        result = {
            "disks": {},
            "lang": "zh",
            "leftDisk": None,
            "rightDisk": None,
            "windowsConfig": 1
        }

        # 这里需要过滤，有些目录只能管理员才能查看
        p = Path(disk_root)
        for child in p.iterdir():
            if child.is_dir():
                result["disks"].update({
                    child.name: { "driver": "local" }
                })

        return result

    '''
    @description: 获取当前类别的目录信息
    @param {*} self
    @return {*}
    '''
    def content(self, disk, target_path='/'):
        '''
        目录信息结构体：
        {
            basename: "docs"
            dirname: ""
            path: "docs"
            timestamp: 1556821372
            type: "dir"
        },
        {
            basename: "cars"
            dirname: "wallpapers"
            path: "wallpapers/cars"
            timestamp: 1544277291
            type: "dir"
        }

        文件信息结构体：
        {
            basename: "alfa.sql"
            dirname: "code"
            extension: "sql"
            filename: "alfa"
            path: "code/alfa.sql"
            size: 3208
            timestamp: 1544277274
            type: "file"
        }
        '''

        target_path = Path(target_path)
        result = {
            "directories": [],
            "files": []
        }

        disk_path = Path(disk_root).joinpath(disk)
        if not disk_path.exists():
            return result
            
        target_path = disk_path.joinpath(target_path)
        if not target_path.exists():
            return result

        for child in target_path.iterdir():
            if child.is_dir():
                result["directories"].append({
                    "basename": child.name,
                    "dirname": child.parent.relative_to(disk_path).as_posix(),
                    "path": child.resolve().relative_to(disk_path).as_posix(),
                    "timestamp": int(child.stat().st_mtime),
                    "type": "dir"
                })
            else:
                result["files"].append({
                    "basename": child.name,
                    "dirname": child.parent,
                    "extension": child.suffix[1:],
                    "filename": child.stem,
                    "path": child.resolve().relative_to(disk_path).as_posix(),
                    "size": child.stat().st_size,
                    "timestamp": int(child.stat().st_mtime),
                    "type": "file"
                })

        with open("result.json", "w") as f:
            json.dump(result, f)
            f.seek(0)
            f.truncate()
            f.write(json.dumps(result, ensure_ascii=True))

        pprint.pprint(result)
        return result

    '''
    @description: 获取目录结构树
    @param {*} self
    @return {*}
    '''
    def tree(self, disk, target_path="/"):
        '''
        {
            basename: "trees"
            dirname: "wallpapers/nature"
            path: "wallpapers/nature/trees"
            props: {
                hasSubdirectories: false
            }
            timestamp: 1544277291
            type: "dir"
        }
        '''

        target_path = Path(target_path)
        result = []
        rp = Path(disk_root)
        disk_path = rp / disk
        if not disk_path.exists():
            return result

        temp_path = disk_path.joinpath(target_path)
        if not temp_path.exists():
            return result

        p = Path(disk_path)
        for child in p.iterdir():
            if child.is_dir():
                result.append({
                    "basename": child.name,
                    "dirname": child.parent.relative_to(rp).as_posix(),
                    "path": child.relative_to(rp).as_posix(),
                    "props": {
                        "hasSubdirectories": True if os.listdir(child.resolve()) else False
                    },
                    "timestamp": int(child.stat().st_mtime),
                    "type": "dir"
                })
            # print("//////////", child.is_dir(), child.resolve(), child.name, child.parent, child.root, child.relative_to(rp))
        pprint.pprint(result)

        return result

fileManager = FileManager()

if __name__ == "__main__":
    '''
    python -m memory_profiler example.py
    '''
    # from memory_profiler import profile
    # @profile
    # def test():
    #     pass

    result = fileManager.initialize()
    print("----->", result)
    
    result = fileManager.content("uploads", "evueapps/evm")
    print(">>>>>>", result)

    result = fileManager.tree("uploads", "evueapps/evm")
    print("=====>", result)