import { faceShareRedirectUrl } from '@/http/configAPI'
import { getChromeStorage } from '@/uilts/chromeExtension.js'

let tempData = {
    isSetContent: false
}

/**
 * 初始化contentjs调用逻辑
 */
export function initFacebookContent() {
    // window.location.href.indexOf('facebook.com') > -1;
    injectShareCode();

    shareCallback();
};

/**
 * 注入分享页面逻辑
 * @returns 
 */
function injectShareCode() {
    const {href, pathname} = window.location;
    if(!(href.indexOf('facebook.com') > -1 && pathname.indexOf('dialog/share') > -1)) {
        return;
    }

    // 设置分享内容
    setShareInputContent();
}

/**
 * 格式化发布内容字符串
 */
function formatContentStr(content) {
    let str = content.replace(/(\r)/g,'\n');
    return str;
}


/**
 * 设置分享输入框内容
 */
async function setShareInputContent() {
    let shareData = await getChromeStorage('shareFacebookData') || {};
    const contentStr = formatContentStr(shareData.contentStr);

    if (!tempData.isSetContent && contentStr) {
        tempData.isSetContent = true;
        document.execCommand("insertText", false, contentStr);
        setTimeout(() => {
            tempData.isSetContent = false;
        }, 300)
    }
}

/**
 * 分享回调
 */
function shareCallback() {
    if (window.location.href.indexOf(faceShareRedirectUrl) > -1) {
        const urlParams = new URLSearchParams(window.location.search);
        let params = JSON.parse(urlParams.get('params'));
        if (params) {
            chrome.storage.local.remove("shareFacebookData");
            chrome.runtime.sendMessage({ actionType: "CONTENT_FACEBOOK_SHARE_SUCCESS", data: params }, () => { 

            })
        }
    }
}