import json
import os
import pypinyin

'''
根据书签文件地址和要搜素的关键字，搜索结果
返回搜索后按创建时间倒序排列的列表供data_handle处理
'''
class bookmark_searcher(object):
    # windows
    bookmark_name = os.path.join(os.path.expanduser("~"), 'AppData//Local//Google//Chrome//User Data//Default', 'Bookmarks')
    # mac
    # bookmark_name = os.path.join(os.path.expanduser("~"), 'Library/Application Support/Google/Chrome/Default',
    #                     'Bookmarks')

    def __init__(self, key: str, bookmark_file_path=bookmark_name):
        self.key = key.strip()
        self.lis = []
        # if "Chrome" in bookmark_file_path or "Edge" in bookmark_file_path:  # 解析字典到包含children这个key的那一层
        if any(bower in bookmark_file_path for bower in ['Chrome', 'Edge']):
            data = self.load(bookmark_file_path)
            for key1, value in data.items():
                if isinstance(value, dict):
                    for key2, value2 in value.items():
                        if isinstance(value2, dict):
                            self.make_list_chrome2(value2)
        elif "Firefox" in bookmark_file_path:  # firefox第一层就是，不用处理
            data = self.jsonlz4_to_text(bookmark_file_path)
            self.make_list_firefox2(data)

    def store(self, data, store_name='data.json'):
        with open(store_name, 'w') as json_file:
            json_file.write(json.dumps(data))

    def load(self, load_name):
        with open(load_name, encoding='UTF-8') as json_file:
            data = json.load(json_file)
            return data

    def make_list_chrome2(self, dic, default_path=''):  # 这里传入字典，非list
        if 'url' in dic.keys() and self.pinyin_item2(self.key, dic['name'], dic['url']):
            self.lis.append([dic['name'], dic['url'], default_path, dic['date_added']])
        elif 'children' in dic.keys():
            default_path += '/' + dic['name']
            for children in dic['children']:
                self.make_list_chrome2(children, default_path)

    def make_list_firefox2(self, dic, default_path=''):
        if 'uri' in dic.keys() and self.pinyin_item2(self.key, dic['title'], dic['uri']):
            self.lis.append([dic['title'], dic['uri'], default_path, dic['dateAdded']])
        elif 'children' in dic.keys():
            default_path += '/' + dic['title']
            for children in dic['children']:
                self.make_list_firefox2(children, default_path)

    def get_child(self):
        pass

    def pinyin_item2(self, key: str, name:str, url: str):
        all_py_spec = ''
        pl = pypinyin.pinyin(name.replace(' ', ''), style=pypinyin.NORMAL)
        first_str = ''
        all_py = ''
        for i in pl:
            first_str += i[0][0]
            all_py += i[0]
            all_py_spec = all_py_spec + i[0] + " "
        all_py_spec = all_py_spec.strip()
        res_pin = all_py_spec + ' ' + first_str + ' ' + all_py
        if res_pin.find(key.lower()) != -1 or name.lower().find(key.lower()) != -1 or \
            url.lower().find(key.lower()) != -1:
            return True
        return False

    def jsonlz4_to_text(self, filepath):
        """
        解析jsonlz4文件，返回json字典
        # Given the path to a "mozlz4", "jsonlz4", "baklz4" etc. file,
        # return the uncompressed text.
        :param filepath:
        :return:
        """
        import lz4.block as lz4
        bytestream = open(filepath, "rb")
        bytestream.read(8)  # skip past the b"mozLz40\0" header
        valid_bytes = bytestream.read()
        text = lz4.decompress(valid_bytes).decode('UTF-8')
        dic = json.loads(text)
        return dic

    def do_search(self):
        # 按添加书签的时间倒序排序
        search_result = sorted(self.lis, key=lambda x: x[3], reverse=True)
        return [x[:3] for x in search_result]


if __name__ == "__main__":
    print(bookmark_searcher('电视').do_search())