// 此文件不要写具体逻辑，只调用函数
import {
    twitterShortUrl,
    twitterPinLoginToken,
    twitterPinLoginCode,
    onInstalledMid,
    onInstalledUserSet,
    onInstalledCreateTab,
    checkPined,
    popupRePublish,
    setBadgeInfo,
    hideBadge,
    setMessageCount,
    discordLoginCode,
    saveDiscordAuthWindowId,
    onDisconnectHandler,
    getMessageInfo,
    injectExtensionPopup,
    setPopupConfig,
    windwoLoadSetPopupPage,
    setActionPopup,
    getTwitterNftPostPre,
    nftTxtPublish,
    getSysMessage,
    checkShowPublishDialog
} from "@/logic/background/twitter";
import Report from "@/log-center/log"
import { PingPong, httpNetWork, httpContentToBack } from "@/logic/background/help";
import { appVersionCode } from '@/http/configAPI.js'
import { getChromeStorage, setChromeStorage } from '@/uilts/chromeExtension.js'

import {
    facebookShareSuccess
} from "@/logic/background/facebook";

import {
    closeAchPayNoticeHandler
} from "@/logic/background/denet";

//加载bg.js 执行
setMessageCount();

// 消息通讯
chrome.runtime.onConnect.addListener(function (port) {
    port.onDisconnect.addListener(function () {
        onDisconnectHandler(port);
    });
});

// 当有可用更新时触发
chrome.runtime.onUpdateAvailable.addListener(() => {
    try {
        Report.reportLog({
            objectType: Report.objectType.background_function_try,
            funcName: 'onUpdateAvailable'
        });
        chrome.runtime.reload()
    } catch (error) {
        Report.reportLog({
            objectType: Report.objectType.background_function_catch,
            funcName: 'onUpdateAvailable',
            errMsg: error.message
        });
    }

})

chrome.runtime.onInstalled.addListener(onInstalledMethod);

chrome.runtime.onMessage.addListener(onMessageMethod);

// 定时器
chrome.alarms.onAlarm.addListener(function (alarm) {
    // console.log("onAlarm-", alarm);
    switch (alarm.name) {
        case 'denetChromeAlarm':
            getMessageInfo();
            break
        case 'PingPong':
            PingPong()
            break;
        case 'LuckMessage':
            getSysMessage()
            break
    }
});

chrome.action.onClicked.addListener(function (tab) {
    injectExtensionPopup(tab);
});

chrome.tabs.onActivated.addListener(function (activeInfo) {
    setPopupConfig(activeInfo);
})

function thenInstalledMethod() {
    try {

        onInstalledCreateTab()
        onInstalledMid()
        onInstalledUserSet()
        // pingpang
        chrome.alarms.create('PingPong', {
            //1分鐘之後開始(該值不能小於1) 
            delayInMinutes: 2,
            //開始後每一分鐘執行一次(該值不能小于1) 
            periodInMinutes: 4
        });
        chrome.alarms.create('LuckMessage', {
            //1分鐘之後開始(該值不能小於1) 
            delayInMinutes: 1,
            //開始後每一分鐘執行一次(該值不能小于1) 
            periodInMinutes: 1
        });
    } catch (error) {
        Report.reportLog({
            objectType: Report.objectType.background_function_catch,
            funcName: 'onInstalledMethod',
            errMsg: error.message
        });
    }
}
function onInstalledMethod() {
    // 版本更新判断
    getChromeStorage('baseInfo', (info) => {
        if (!info || !info.appVersionCode) {
            setChromeStorage({ baseInfo: JSON.stringify({ appVersionCode }) })
            thenInstalledMethod()
        } else if (appVersionCode != info.appVersionCode) {
            setChromeStorage({ baseInfo: JSON.stringify({ appVersionCode }) }, () => {
                chrome.runtime.reload()
            })
        } else {
            thenInstalledMethod()
        }
    })
}

function onMessageMethod(req, sender, sendResponse) {
    try {

        if (req) {
            switch (req.actionType) {
                case "POPUP_LOGIN":
                    twitterPinLoginToken();
                    break;
                case "POPUP_PUBLISH_TWITTER_RED_PACK":
                    popupRePublish(req);
                    break;
                case "POPUP_SHOW_DENET_PUBLISH_DIALOG":
                    checkShowPublishDialog();
                    break;
                case 'CONTENT_GET_PINED':
                    checkPined();
                    break;
                case 'CONTENT_SET_BADGE':
                    setBadgeInfo(req);
                    break;
                case 'CONTENT_HIDE_BADGE':
                    hideBadge();
                    break
                case 'CONTENT_SEND_CODE':
                    twitterPinLoginCode(sender, req.code);
                    break;
                case 'CONTENT_TWITTER_LOGIN':
                    if (req.data) {
                        twitterPinLoginToken()
                    }
                    break
                case "CONTENT_SEND_DISCORD_AUTH_CODE":
                    discordLoginCode(req, sender);
                    break
                case 'RED_PACKET_SAVE_DISCORD_AUTH_WINDOW_ID':
                    saveDiscordAuthWindowId(req);
                    break;
                case 'CONTENT_FACEBOOK_SHARE_SUCCESS':
                    facebookShareSuccess(req, sender);
                    break;
                case 'CONTENT_PONG':
                    console.log('CONTENT_PONG')
                    break
                case 'CONTENT_WINDOW_LOADED_SET_POPUP_PAGE':
                    // windwoLoadSetPopupPage(req, sender);
                    break;
                case 'CONTENT_SET_POPUP_CONFIG':
                    setActionPopup(req, sender);
                    break;
                case 'CONTENT_GET_TWITTER_NFT_POST_PRE':
                    getTwitterNftPostPre(req.data, sender)
                    break
                case 'CONTENT_NFT_TXT_PUBLISH':
                    nftTxtPublish(req.data, sender)
                    break
                case 'CONTENT_HTTP_NET_WORK':
                    httpNetWork(req.funcName, req.data, sender)
                    break
                case 'HTTP_CONTENT_TO_BACK':
                    httpContentToBack(req, sender)
                    break
                case 'CONTENT_TWITTER_SHORT_LINK':
                    sendResponse('ok')
                    req.arr_url.forEach(item => {
                        if (item) {
                            twitterShortUrl(sender, item)
                        }
                    });
                    break
                case 'CONTENT_CLOSE_ACH_PAY_NOTICE':
                    closeAchPayNoticeHandler();
                    break;
            }
        }
    } catch (error) {
        Report.reportLog({
            objectType: Report.objectType.background_function_catch,
            funcName: 'onMessageMethod',
            errMsg: error.message
        });
    }
}
