# -*-coding:utf-8-*-
import os
import threading
from bookmark_searcher import bookmark_searcher

'''
将多个浏览器的书签地址放在list，根据list多线程调用bookmark_searcher处理数据使用
返回easygo可直接使用的结果数据列表
'''
class data_handle(object):
    def __init__(self):
        self.bookmark_list_result = []

    def get_bookmarks_paths(self):
        user_home = os.path.expanduser("~")
        # chrome的书签是一个文件，文件名固定，且该文件夹下有很多其他文件，素以需要确切的文件名
        chrome_bookmark_name = os.path.join(user_home, 'AppData//Local//Google//Chrome//User Data//Default', 'Bookmarks')
        edge_bookmark_name = os.path.join(user_home, 'AppData//Local//Microsoft//Edge//User Data//Default', 'Bookmarks')
        path_list = [chrome_bookmark_name]
        path_list.append(edge_bookmark_name)
        # firefox是解析书签备份文件，对应文件夹下只有书签文件，但不止一个，名字不确定，我们只需要书签文件夹那一层就行，然后获取最新那个备份文件
        firefox_profiles_path = os.path.join(user_home, 'AppData\\Roaming\\Mozilla\\Firefox\\Profiles')
        for root_path, dirs, files in os.walk(firefox_profiles_path):  # 遍历获取火狐书签备份路径，不同电脑的备份路径名不一致，中间有一节目录是随机的
            if 'bookmarkbackups' in dirs:
                firefox_bookmarks_path = os.path.join(root_path, 'bookmarkbackups')
                lists = os.listdir(firefox_bookmarks_path)
                lists.sort(key=lambda fn: os.path.getmtime(firefox_bookmarks_path + "\\" + fn))  # 获取最新的书签备份
                firefox_bookmark_name = os.path.join(firefox_bookmarks_path, lists[-1])
                if firefox_bookmark_name:
                    path_list.append(firefox_bookmark_name)
        return path_list

    def search(self, path: str, query: str):
        if "Chrome" in path:
            browser = "Chrome"
            ico = "chrome.ico"
        elif "Firefox" in path:
            browser = "Firefox"
            ico = "firefox.ico"
        elif "Edge" in path:
            browser = "Edge"
            ico = "edge.png"
        else:
            ico = "default.png"

        if query:
            bookmark_list = bookmark_searcher(query, path).do_search()
            if not bookmark_list:
                self.bookmark_list_result.insert(0, {
                    "Title": "None",
                    "SubTitle": "In {} Query: {}".format(browser, query),
                    "IconPath": "Images/default.png"
                })
                return self.bookmark_list_result
            for item in bookmark_list:
                path = item[2]
                title = item[0]
                url = item[1]
                self.bookmark_list_result.append({
                    "Title": '{}'.format(title),
                    "SubTitle": "{}".format(url),
                    "IconPath": "Images/{}".format(ico),
                    "ExtraData": "{}".format(path),
                    "Action": {
                        "FuncName": "openUrl",
                        "Parameter": url
                    }
                })
        return self.bookmark_list_result

    def get_bookmarks(self, query: str):
        threads = []
        for i in self.get_bookmarks_paths():
            t = MyThread(self.search, (i, query,), self.search.__name__)
            threads.append(t)
        for i in threads:  # start threads 此处并不会执行线程，而是将任务分发到每个线程，同步线程。等同步完成后再开始执行start方法
            i.start()
        for i in threads:  # jion()方法等待线程完成
            i.join()
        return threads[0].get_result()  # 这里获取到的是所有线程的返回结果


class MyThread(threading.Thread):
    def __init__(self, func, args, name=''):
        threading.Thread.__init__(self)
        self.name = name
        self.func = func  # 要有这句，不然还以一个一个执行，不会一起执行
        self.args = args
        # self.result = self.func(*self.args)

    def run(self):
        self.result = self.func(*self.args)

    def get_result(self):
        try:
            return self.result
        except Exception:
            return None


if __name__ == '__main__':
    print(data_handle().get_bookmarks("电视节"))
    for root, path, name in os.walk("C:\\Users\\wwwxi\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles"):
        if 'bookmarkbackups' in path:
            book_path = os.path.join(root, 'bookmarkbackups')