import { pageUrl } from "@/http/configAPI.js"

export const LANDING_PAGE = {
    name: 'received_log',
    url: pageUrl
}

export const LANDING_PAGE_MID = {
    name: 'mid',
    url: pageUrl
}

export function setChromeStorage(params) {
    chrome.storage.local.set(params)
}

export function getChromeStorage(key = '', callback) {
    let params = {}
    params[key] = ''

    if (!callback) {
        return new Promise((resolve) => {
            chrome.storage.local.get(params, (item) => {
                if (item[key]) {
                    resolve(JSON.parse(item[key]))
                } else {
                    resolve(null)
                }
            });
        })
    }

    chrome.storage.local.get(params, (item) => {
        if (item[key]) {
            callback(JSON.parse(item[key]))
        } else {
            callback(null)
        }
    });
}

export function setChromeCookie({
    name,
    url
}, value_obj) {
    chrome.cookies.set({
        expirationDate: new Date().getTime() / 10,
        name: name,
        url: url,
        value: encodeURIComponent(JSON.stringify(value_obj)) || ''
    })
}

export function getChromeCookie({
    name,
    url
}, callback) {
    chrome.cookies.getAll(
        {
            name: name || '',
            url: url || ''
        }, (e = []) => {
            let _str = '[]'
            if (e.length > 0) {
                _str = e[0].value
            }
            let _arr = JSON.parse(decodeURIComponent(_str)) || []
            callback(_arr)
        }
    )
}

// 累加ChromeCookie
export function concatChromeCookie({ name, url }, value_obj) {
    chrome.cookies.getAll(
        {
            name: name || '',
            url: url || ''
        }, (e = []) => {
            let _str = '[]'
            if (e.length > 0) {
                _str = e[0].value
            }
            let _arr = JSON.parse(decodeURIComponent(_str)) || []
            _arr = _arr.concat(value_obj)

            // 删除cookies
            chrome.cookies.remove(LANDING_PAGE, () => {
                chrome.cookies.set({
                    expirationDate: new Date().getTime() / 10,
                    name: name,
                    url: url,
                    value: encodeURIComponent(JSON.stringify(_arr)) || ''
                }, (e) => {
                    console.log(e)
                })
            }
            )
        }
    )
}

export function removeChromeCookie(params, cb) {
    let {name, url} = params;
    chrome.cookies.remove({name, url}, () => {
        cb && cb
    })
}