

//var token_line="";
chrome.runtime.onInstalled.addListener(function(object) {
    chrome.storage.local.get('installed', function(a) {
        if (!a.installed) {
            // after installing open main web site
            chrome.storage.local.set({
                'installed': true
            }, function() {});
        }
    });
});

function getOriginFromUrl(inp) {
    try {
        var url = new URL(inp);
        var full = url.protocol + '//' + url.hostname + (url.port ? ':' + url.port : '');
		//if (!window.location.origin) {
			//window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port: '');
		//}
        return full;
    } catch (e) {
        return "";
    }
}

chrome.webRequest.onBeforeSendHeaders.addListener(
    function(info) {
        if (info.initiator == 'chrome-extension://' + chrome.runtime.id) {
            var originSet = null;
            var refererSet = null;
            var cookieSet = null;
            var originSet = null;
            var refererSet = null;
            for (var index = 0; index < info.requestHeaders.length; index++) {
                //console.log(info.requestHeaders[index].name);
                if (info.requestHeaders[index].name.toLowerCase() === 'origin') {
                    info.requestHeaders[index].value = getOriginFromUrl(info.url);
                    originSet = true;
                }
                if (info.requestHeaders[index].name.toLowerCase() === 'referer') {
                    info.requestHeaders[index].value = getOriginFromUrl(info.url);
                    refererSet = true;
                }
            }
            if (!originSet) {
                info.requestHeaders.push({
                    'name': 'Origin',
                    'value': getOriginFromUrl(info.url),
                });
            }
            if (!refererSet) {
                info.requestHeaders.push({
                    'name': 'Referer',
                    'value': getOriginFromUrl(info.url),
                });
            }
            return {
                requestHeaders: info.requestHeaders
            };
        }
    }, {
        urls: ['*://*.facebook.com/*']
    },
    ['blocking', 'requestHeaders', 'extraHeaders']
);

/*
//////Get Line Token Line Here
chrome.webRequest.onHeadersReceived.addListener(function(details) {
    //console.log(details);
    var redirUrl;
	localStorage.setItem('token_line', token_line)	//clear token_line
    details.responseHeaders.forEach(function(v, i, a) {
        if (v.name.toLowerCase() == "location") {
            redirUrl = v.value;
            if (redirUrl != '') {
				if(redirUrl.substr(0,21)=="https://chat.line.biz"){
					redirUrl = redirUrl.replace('https://chat.line.biz/', '');
					if(redirUrl!=""){
						token_line=redirUrl;
						localStorage.setItem('token_line', token_line)	//save token_line from my_broadcast_lineOa.js
						//console.log(token_line);
						//sessionStorage.setItem("token_line", token_line);
						// Retrieve
						//console.log(sessionStorage.getItem("token_line"));

					}
				}
				//console.log('localStorage.setItem("token_line"):'+redirUrl);
            }
        }
    });

}, {
    urls: ['*://chat.line.biz/account/*']
}, ["responseHeaders", "blocking"]);
*/

chrome.webRequest.onBeforeSendHeaders.addListener(
    function(info) {
        if (info.initiator == 'chrome-extension://' + chrome.runtime.id) {
            var originSet = null;
            var refererSet = null;
            var cookieSet = null;
            var originSet = null;
            var refererSet = null;
            for (var index = 0; index < info.requestHeaders.length; index++) {
                //console.log.log(info.requestHeaders[index].name + '------' + info.requestHeaders[index].value);
                if (info.requestHeaders[index].name.toLowerCase() === 'origin') {
                    info.requestHeaders[index].value = getOriginFromUrl(info.url);
                    originSet = true;
                }
                if (info.requestHeaders[index].name.toLowerCase() === 'referer') {
                    info.requestHeaders[index].value = getOriginFromUrl(info.url);
                    refererSet = true;
                } else {
                    if (info.requestHeaders[index].name.toLowerCase() === 'cookie') {
                        //path =  info.requestHeaders[index].value.split('"path":"')[1].split('"')[0];
                        //alert(path);
                    }
                }
            }
            if (!originSet) {
                info.requestHeaders.push({
                    'name': 'Origin',
                    'value': getOriginFromUrl(info.url),
                });
            }

            if (!refererSet) {
                info.requestHeaders.push({
                    'name': 'Referer',
                    'value': getOriginFromUrl(info.url),
                });
            }
            return {
                requestHeaders: info.requestHeaders
            };
        }
    }, {
        urls: ['*://chat.line.biz/*']
    },
    ['blocking', 'requestHeaders', 'extraHeaders']
);

chrome.browserAction.onClicked.addListener(function(e) {
	chrome.tabs.create({
		url: chrome.extension.getURL("index.html")
		//url: chrome.extension.getURL("index.html")
		,active: !0
	});
	return true
	/*
    chrome.tabs.create({
		url: chrome.extension.getURL("index.html#openbroadcast")
		,active: !0
	}, function(t) {
		chrome.windows.getCurrent(function(e) {
			var n = e.width / 2 - 620 + e.left,
				r = e.height / 2 - 250 + e.top;
			chrome.windows.create({
				tabId: t.id,
				type: "popup",
				focused: !0,
				width: 1245,	//screen.width,//
				height: 610,	//screen.height,//
				left: Math.round(n),	//0,//
				top: Math.round(r)	//0//
			}, function(t) {
				i = t.id
				chrome.windows.update(i,{state:"maximized"},function(windowUpdated){
					//do whatever with the maximized window
					//console.log(windowUpdated);
				});
				
			})
		})
	});
	*/
});

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.type == "get") {
        var url = request.url;
        fetch(url)
            .then(response => response.text())
            .then(response => sendResponse(response))
            .catch()
        return true;
    }

    if (request.type == "post") {
        fetch(request.url, {
                method: 'POST',
                headers: {
                    'Accept': 'application/json, application/xml, text/plain, text/html, *.*',
                    'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
                },
                body: request.data
            })
            .then(response => response.text())
            .then(response => sendResponse(response))
            .catch(error => console.log('Error:', error));
        return true;
    }

    if (request.type == "post_upload") {

        //console.log.log(request.data)

        return true;

    }

    return true;
});
