# -*- coding: utf-8 -*-

"""
    Bxplorer 的数据
"""

import os
import json

from PyQt5.QtWidgets import QApplication

from file_reader import FileReader
from progress_bar import ProgressBar

INIT_FILE_NAME = 'BXPLORE.DATA'
INIT_FILE_DATA = {
    'File': {},
    'Root': [],
    'Property': {
        'name': ['名称', '主演', '地域', '无马', '字幕', '分类', '标签', '播放', '操作', '大小', '格式', '路径'],
        'length': [200, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    },
    'Choices': {
        '地域': ['', '大陆', '日本', '韩国', '欧美'],
        '无马': ['', 'YES', 'NO'],
        '字幕': ['', 'YES', 'NO'],
        '分类': ['', 'OL', '学生', '护士', '风俗娘', '萝莉', '熟女', '公车', '人妻', '家庭', '自拍流出', '剧场', 'Newhalf'],
        '标签': ['', '永久收藏', '精品', '一般', '待删除'],
    },
    'Player': r'D:\Program Files\PotPlayer64\PotPlayerMini64.exe',
    'Backups': {},
}

class BxplorerData():
    ''' Bxplorer的数据操作 '''

    def __init__(self, data_path):

        self.data_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), INIT_FILE_NAME) \
            if data_path is None else data_path

        self.property = INIT_FILE_DATA['Property']
        self.choices = INIT_FILE_DATA['Choices']
        self.player = INIT_FILE_DATA['Player']

        if os.path.isfile(self.data_path):
            if os.path.getsize(self.data_path) == 0:
                self.__new()
            else:
                try:
                    file_read = open(self.data_path, 'r', encoding='utf-8').read()
                    file_data = json.loads(file_read)
                except (TypeError, KeyError, ValueError):
                    self.__backup_and_new()
                for key in INIT_FILE_DATA:
                    if key not in file_data:
                        self.__backup_and_new()
                        continue
        else:
            self.__new()

    def __new(self):
        ''' 创建新数据文件 '''

        file = open(self.data_path, 'w', encoding='utf-8')
        file.write(json.dumps(INIT_FILE_DATA, indent=2, sort_keys=True, ensure_ascii=False))
        file.close()

    def __backup_and_new(self):
        ''' 备份后创建新数据文件 '''

        file_backup = self.data_path + '.bak'
        if os.path.isfile(file_backup):
            os.remove(file_backup)
        os.rename(self.data_path, file_backup)
        self.__new()

    def read(self):
        ''' 读数据 '''

        open_file = open(self.data_path, 'r', encoding='utf-8')
        data = json.load(open_file)
        open_file.close()
        return data

    def write(self, data):
        ''' 写数据 '''

        open_file = open(self.data_path, 'w', encoding='utf-8')
        open_file.write(json.dumps(data, indent=2, sort_keys=True, ensure_ascii=False))
        open_file.close()

    def append_root(self, root):
        ''' 添加一个root '''

        data = self.read()

        # 如果目录已存在，或是现有Root集的子路径，跳出；否则添加目录
        for _root in data['Root']:
            if _root == root or _root in root:
                return
        data['Root'].append(root)

        # 初始化一个进度条
        progress_bar = ProgressBar('Code Files')

        # 添加目录下的所有文件
        file_reader = FileReader()
        file_list = file_reader.walk_folder(root)
        total_number = len(file_list)
        for index, file in enumerate(file_list):

            # 获取文件基本信息
            ## 获取文件标识码
            file_code = file_reader.code_file(file)
            ## 获取文件名和文件扩展名
            file_basename = os.path.basename(file)
            file_name, file_extension = os.path.splitext(file_basename)
            ## 获取文件大小
            file_size_num = (int)(file_code.split('-')[-1])
            file_size_num = round(file_size_num / 1024 / 1024)
            file_size = str(file_size_num) + ' MB' if file_size_num < 1024 \
                else str(round(file_size_num / 1024, 2)) + ' GB'

            # 如果在已有数据中找不到文件，进行添加
            if file not in data['File']:
                data['File'][file] = {
                    'code': file_code,
                    'extension': file_extension,
                    'name': file_name,
                    'path': file,
                    'size': file_size,
                }

            # 进度条即时显示
            progress_bar.set_value(index + 1, total_number)
            QApplication.processEvents()

        # 循环结束，关闭进度条
        progress_bar.close()
        # 回填更新后的数据
        self.write(data)

    def delete_root(self, root):
        ''' 删除一个文件夹 '''

        data = self.read()

        # 删除数据中的文件夹部分
        for _root in data['Root']:
            if root == _root or root in _root:
                data['Root'].remove(_root)

        # 删除数据中的文件部分
        delete_file = []
        for file in data['File']:
            if root in file:
                delete_file.append(file)
        for file in delete_file:
            del data['File'][file]

        # 回填更新后的数据
        self.write(data)

    def update_backups(self, code, key, value):
        ''' 更新备份库 '''

        data = self.read()

        if code in data['Backups']:
            data['Backups'][code][key] = value
        else:
            data['Backups'][code] = {key: value}

        self.write(data)
