!function () {
    chrome.runtime.sendMessage({type: "getBackgroundCacheValue", key: "pddSearchItems"}, async function (pddSearchItems) {
        var imgKeys = ['hd_thumb_url', 'hd_url', 'thumb_url'];
        var pddSearchItems = JSON.parse(pddSearchItems);
        for (let i in pddSearchItems){
            for (let j in imgKeys) {
                var results = pddSearchItems[i][imgKeys[j]].split('/');
                var matchKey = results[results.length - 1].replace(/\..*?$/g, '');
                var imgElem = $('img[data-src*="{0}"]'.format(matchKey));
                if (!imgElem || !imgElem.length){
                    imgElem = $('img[src*="{0}"]'.format(matchKey));
                }
                if (imgElem.length) {
                    if (document.location.href.indexOf('search_result.htm') > -1){
                        var elem = imgElem.parent().parent().parent().parent();
                    } else {
                        var elem = imgElem.parent().parent();
                    }
                    elem.attr('goodsid', pddSearchItems[i]['goods_id']);
                    elem.attr('goodsurl', pddSearchItems[i]['link_url']);
                    elem.attr('renderext', '1');
                    // console.log(pddSearchItems[i]['goods_id']);
                    break;
                }
            }
        }

        if (pddSearchItems.length){
            chrome.runtime.sendMessage({
                type: 'executeScript',
                url: ['server/js/pdd/itemcollect.js']
            });
        }
    });
}();
