const MESSAGE_TYPE = {
    GET_BOOKMARKS_TREE: 'GET_BOOKMARKS_TREE',
    BOOKMARKS_CHANGED: 'BOOKMARKS_CHANGED',
    SUBSCRIBE_BOOKMARKS: 'SUBSCRIBE_BOOKMARKS',
    GET_SEARCH_SUGGESTIONS: 'GET_SEARCH_SUGGESTIONS',
}

let extensionId = chrome.runtime.id;
let connectedPort = null;

function handleMessage(request, sender, sendResponse) {
    if (request.type === MESSAGE_TYPE.GET_BOOKMARKS_TREE) {
        chrome.bookmarks.getTree(function (bookmarkTree) {
            const requestDB = indexedDB.open('BookmarkDB', 1);
            requestDB.onerror = function () {
                sendResponse({ success: false, error: '数据库打开失败' });
            };

            requestDB.onupgradeneeded = function (event) {
                const db = event.target.result;
                if (!db.objectStoreNames.contains('bookmarks')) {
                    db.createObjectStore('bookmarks', { keyPath: 'id' });
                }
            };

            requestDB.onsuccess = function () {
                const db = requestDB.result;
                const transaction = db.transaction(['bookmarks'], 'readwrite');
                const store = transaction.objectStore('bookmarks');

                const bookmarkData = {
                    id: 'root',
                    data: bookmarkTree,
                    timestamp: Date.now()
                };
                store.put(bookmarkData);

                transaction.oncomplete = function () {
                    sendResponse({ success: true, data: bookmarkTree });
                };

                transaction.onerror = function () {
                    sendResponse({ success: false, error: '保存书签失败' });
                };
            };
        });
        return true;
    }

    if (request.type === MESSAGE_TYPE.GET_SEARCH_SUGGESTIONS) {
        var keyword = request.keyword
        var engineId = request.engineId
        fetchSearchSuggestions(keyword, engineId)
            .then(function (suggestions) {
                sendResponse({ success: true, data: suggestions })
            })
            .catch(function (error) {
                sendResponse({ success: false, error: error.message })
            })
        return true;
    }
}


async function fetchSearchSuggestions(keyword, engineId) {
    if (!keyword) return []


    var engines = {
        baidu: 'https://suggestion.baidu.com/su?wd=' + encodeURIComponent(keyword) + '&cb=window.baidu&action=opensearch',
        google: 'https://www.google.com/complete/search?q=' + encodeURIComponent(keyword) + '&cp=1&client=chrome',
        bing: 'https://api.bing.com/osjson.aspx?query=' + encodeURIComponent(keyword),
    }

    var url = engines[engineId]
    if (!url) {
        throw new Error('不支持的搜索引擎: ' + engineId)
    }

    try {
        var response = await fetch(url, {
            headers: {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
                'Accept': '*/*',
                'Referer': 'https://www.baidu.com/',
            }
        })
        if (!response.ok) {
            console.error('请求失败: ', response.status)
            return []
        }

        var text
        if (engineId === 'baidu' || engineId === 'sogou') {
            var buffer = await response.arrayBuffer()
            var decoder = new TextDecoder('gbk')
            text = decoder.decode(buffer)
        } else {
            text = await response.text()
        }

        return parseSuggestions(text, engineId)
    } catch (error) {
        console.error('获取 ' + engineId + ' 建议失败: ', error)
        return []
    }
}


const suggestionParsers = {
    baidu: (text) => {
        if (!text || text.length < 2) return []
        try {
            const match = text.match(/window\.baidu\(\s*(\[[\s\S]*?\])\s*\)/)
            if (match) {
                return JSON.parse(match[1])[1] || []
            }
            const data = JSON.parse(text)
            return Array.isArray(data) ? data[1] || [] : []
        } catch {
            return []
        }
    },
    google: (text) => {
        if (!text || text.length < 2) return []
        try {
            const data = JSON.parse(text)
            if (Array.isArray(data) && data[1]) {
                return data[1]
            }
            const match = text.match(/\[\[(.*?)",/)
            if (match) {
                return match[1].split('","').slice(0, 10)
            }
            return []
        } catch {
            return []
        }
    },
    bing: (text) => {
        if (text[0] !== '[') return []
        try {
            const data = JSON.parse(text)
            return data[1] || []
        } catch {
            return []
        }
    },
}

function parseSuggestions(text, engineId) {
    if (!text || text.length < 2) {
        return []
    }

    const parser = suggestionParsers[engineId]
    if (!parser) {
        console.warn('未找到引擎 ' + engineId + ' 的解析器')
        return []
    }

    try {
        return parser(text)
    } catch (error) {
        console.error('解析 ' + engineId + ' 建议失败: ', error)
        return []
    }
}


function saveBookmarksToDB() {
    chrome.bookmarks.getTree(function (bookmarkTree) {
        const request = indexedDB.open('BookmarkDB', 1);

        request.onerror = function () {
            console.error('数据库打开失败');
        };

        request.onupgradeneeded = function (event) {
            const db = event.target.result;
            if (!db.objectStoreNames.contains('bookmarks')) {
                db.createObjectStore('bookmarks', { keyPath: 'id' });
            }
        };

        request.onsuccess = function (event) {
            const db = event.target.result;
            const transaction = db.transaction(['bookmarks'], 'readwrite');
            const store = transaction.objectStore('bookmarks');

            store.clear();
            let arr = []
            if (bookmarkTree.length === 1) {
                arr = bookmarkTree[0].children
            } else {
                arr = bookmarkData
            }
            const bookmarkData = {
                id: 'root',
                data: arr,
                timestamp: Date.now()
            };
            store.add(bookmarkData);

            transaction.oncomplete = function () {
                saveExtensionIdToDB();
            };

            transaction.onerror = function () {
                console.error('书签数据预加载失败');
            };
        };
    });
}


function saveExtensionIdToDB() {
    const request = indexedDB.open('BookmarkDB', 1);

    request.onerror = function () {
        console.error('数据库打开失败');
    };

    request.onupgradeneeded = function (event) {
        const db = event.target.result;
        if (!db.objectStoreNames.contains('bookmarks')) {
            db.createObjectStore('bookmarks', { keyPath: 'id' });
        }
    };

    request.onsuccess = function (event) {
        const db = event.target.result;
        const transaction = db.transaction(['bookmarks'], 'readwrite');
        const store = transaction.objectStore('bookmarks');

        store.put({
            id: 'extensionId',
            value: extensionId,
            timestamp: Date.now()
        });

        transaction.oncomplete = function () {
            console.log('Extension ID 已保存到数据库:', extensionId);
        };

        transaction.onerror = function () {
            console.error('保存 Extension ID 失败');
        };
    };
}


chrome.runtime.onInstalled.addListener(function () {
    saveBookmarksToDB();
});

chrome.runtime.onStartup.addListener(function () {
    saveBookmarksToDB();
});

chrome.action.onClicked.addListener(function () {
    saveBookmarksToDB();
    const url = chrome.runtime.getURL('dist/index.html');
    chrome.tabs.create({ url });
});
chrome.runtime.onMessage.addListener(handleMessage);
chrome.runtime.onConnect.addListener(function (port) {
    connectedPort = port;
});
