import { commonFetch } from '@/http/fetch'

// 每4分钟调用一次，保持background一直有效
export function PingPong() {
    chrome.tabs.query({}, (tabs = []) => {
        if (tabs.length) {
            let tab = tabs.filter((item) => { return item.active == true })
            if (tab.length) {
                chrome.tabs.sendMessage(tab[0].id, { actionType: 'BACK_PING' }, () => { });
            }
        }
    })
}

export function httpNetWork(funcName, data, sender) {
    return commonFetch(data)
        .then((response) => {
            chrome.tabs.sendMessage(sender.tab.id, { actionType: 'BACK_HTTP_RESPONSE', data: response, funcName });
        })
        .catch(() => {
            chrome.tabs.sendMessage(sender.tab.id, { actionType: 'BACK_HTTP_RESPONSE', data: null, funcName });
        })
}

// 向content 发送消息
export const setContentMessage = (obj) => {
    chrome.tabs.query({}, (tabs = []) => {
        if (tabs.length) {
            tabs = tabs.filter((item) => { return item.active && item.selected && item.highlighted }) || []
            tabs.forEach((item) => {
                chrome.tabs.sendMessage(item.id, obj);
            })
        }
    })
}

export const httpContentToBack = (req, sender) => {
    commonFetch(req.data)
        .then((response) => {
            chrome.tabs.sendMessage(sender.tab.id, { actionType: 'HTTP_BACK_TO_CONTENT', data: response, callback_id: req.callback_id });
        })
        .catch(() => {
            chrome.tabs.sendMessage(sender.tab.id, { actionType: 'HTTP_BACK_TO_CONTENT', data: null, callback_id: req.callback_id });
        })
}