
/**
 * 
 * Content Script for backgroud page of Digpedia Chrome extension 
 * Permissions required: tabs, storage
 * @version 2.1
 * @author Massimiliano Battan
 * 
 */


var regexp = new RegExp("http[s]?:\/\/(([a-z]{2})\.)?wikipedia\.org\/wiki\/(.*)");


chrome.pageAction.onClicked.addListener(function () {
    chrome.windows.create({'url': chrome.extension.getURL('index.html'),'width':880,'height':750},function (win) {
 
    })

});

/**
 * Listener to get any URL change in any tab.
 * @param {type} param
 */
chrome.tabs.onUpdated.addListener(function (tabId, info, tab) {
    if (info.status == 'complete') { //just do this on complete status
        var r = matchUrl(tab.url, tabId);
        if (r != null) {
            saveResource(r);
        }
    }
});

/**
 * Save in chrome local storage an object of the current wikipedia page. It will be used by 
 * the popup page to bootstrap angular application
 * @param {type} r
 */
function saveResource(r) {
    console.log(r.tabId);
    var resource = {"name": r.resource, "locale": r.locale, "id": ""};
    chrome.storage.local.set(resource, function () {
        chrome.pageAction.show(r.tabId);
    });
}

/**
 * Check the current URL if match a wikipedia resource page
 * @param {type} url used
 * @param {type} id id of current tab
 * @returns result obj containing resource name, locale and id of the tab
 */
function matchUrl(url, id) {
    var result = {
        "resource": "",
        "locale": "",
        "tabId": id};
    var match = regexp.test(url);
    if (match) {
        var res = regexp.exec(url);
        result.resource = res[3];
        result.locale = res[2];
        if (result.resource != undefined) {
            if (result.resource != "") {
                if (result.locale === undefined) {
                    result.locale = en;
                }
                return result;
            }
        }
    }
    return null;
}

/**
 * Listener needed in the case the user moves between tabs containing wikipeddia pages. W/o this, the popup
 * would init always with the URL of the last wikipedia created (thus, not the current tabs the user is on)
 * @param {type} param
 */
chrome.tabs.onHighlighted.addListener(function (obj) {
    var tabId = obj.tabIds[0];
    if (tabId != undefined) {
        chrome.storage.local.get("id", function (data) {
            if (data.id == undefined) {
                //just do nothing
            } else if (data.id == tabId) {
                //do nothing
            } else {
                // ids dont match. If i'm in a wiki page now, I should update the local storage
                var tab = chrome.tabs.get(tabId, function (tab) {
                    var r = matchUrl(tab.url, tabId);
                    if (r != null) {
                        saveResource(r);
                    }
                })
            }
        });
    }
});

