# -*- coding: UTF-8 -*-
import json

from PythonPlugin import PythonPlugin, PythonPluginAPI


class Main(PythonPlugin):
    filename = "../../Settings/ThemeSetting.json"
    jdata = {}

    def Query(self, key):
        results = []
        self.load_file()
        results = self.list_items(key)
        return results

    def load_file(self):
        with open(self.filename, "r",  encoding="utf_8_sig") as f:
            self.jdata = json.loads(f.read())

    def list_items(self, key):
        results = []
            
        results.append({
            "Title": '目前主题是：'+(self.jdata['CurrentSelect'] if self.jdata['CurrentSelect'] else '默认主题'),
            "SubTitle": '点击/回车选择列表中主题后重启/重载软件才生效',
            "IconPath": ""
        })
        
        results.append({
            'Title': '默认主题',
            'SubTitle': '默认主题',
            "IconPath": "",
            "Action": {
                "FuncName": "act_select_item",
                "Parameter": json.dumps([key, ""]),
                'HideWindow': False
            }
        })
            
        for theme in self.jdata['Themes']:
            results.append({
                'Title': '{Name}'.format(**theme),
                'SubTitle': '{Description}'.format(**theme),
                "IconPath": "",
                "Action": {
                    "FuncName": "act_select_item",
                    "Parameter": json.dumps([key, theme['Name']]),
                    'HideWindow': False
                }
            })
        return results

    def act_select_item(self, param):
        self.load_file()
        key = json.loads(param)[0]
        name = json.loads(param)[1]
        with open(self.filename, "w", encoding="utf-8") as f:
            self.jdata['CurrentSelect'] = name
            f.write(json.dumps(self.jdata, ensure_ascii=False, indent=4))
        PythonPluginAPI.ReQuery()
        PythonPluginAPI.Reload()

if __name__ == "__main__":
    Main()

    # 每次查询（包括进入Action）后self.xx变量都会初始化
    #  import re if re.search(r'^d', key.strip(), re.I):
    #     return  self.list_delete_tips()+results
    # else:

    # def list_delete_tips(self):
    #     tips = self.get_tips()
    #     results = []
    #     for tip in tips:
    #         results.append({
    #             "Title": "delete %s" % tip['tip'],
    #             "SubTitle": tip['updated_time'],
    #             "IconPath": "Images/pic.png",
    #             "Action": {
    #                 "FuncName": "delete_tip",
    #                 "Parameter": tip['updated_time'],
    #                 "HideWindow": False
    #             }
    #         })
    #     return results

    # def delete_tip(self, times):
    #     try:
    #         tips = []
    #         with open(self.TIPS_FILE, "r") as f:
    #             for line in f:
    #                 tips.append(json.loads(line.strip()))
    #         for tip in tips:
    #             if times == tip["updated_time"]:
    #                 tips.remove(tip)
    #                 break
    #         with open(self.TIPS_FILE, "w") as f:
    #             for tip in tips:
    #                 f.write(json.dumps(tip) + "\n")
    #         PythonPluginAPI.ChangeQuery("tip")
    #     except:
    #         logging.error(traceback.format_exc())
