
var token_line="";
var lineMeCookie={};
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/*','*://*.line.biz/*']
}, ["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') {
                        console.log(info);
                        //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/*',"*://*.line.biz/*"]
    },
    ['blocking', 'requestHeaders', 'extraHeaders']
);

function getLineMeCookie(){
	lineMeCookie={};
    let domain = "line.biz";
	return new Promise(async resolve =>{
		try{
            chrome.cookies.getAll({domain:"line.biz"}, function (cookies) {
                var a = [];
                    //log("@getCookies. Cookies found " +  cookies.length);
                    console.log("@getCookies. Cookies found " +  cookies.length);
                    cookies.forEach(function(cookie) {
                        console.log("[COOKIE] => " + JSON.stringify(cookie));
                        a.push({
                            name: cookie.name,
                            value: cookie.value,
                            domain: cookie.domain,
                            secure: cookie.secure,
                            path: cookie.path
                        });
                        if(cookie.domain=="chat."+domain && cookie.name=="XSRF-TOKEN"){
                            lineMeCookie.xsrf=cookie.value;
                        }else if(cookie.domain=="."+domain && cookie.name=="ses"){
                            lineMeCookie.ses=cookie.value;
                        }
                    });
                    //results[tabId].cookies = a;
                    console.log(lineMeCookie);
                    console.log(a);
                    resolve(lineMeCookie);
                }
            );
            
            /*
			const all_cookies = await chrome.cookies.getAll({domain:"line.biz"});
			console.log(all_cookies);
			if (all_cookies.length === 0) {
				return "No Line OA's token found.";
			}else{
				let cookie = "";
				var count = all_cookies.length;
				cookie = "{\n";
				for (var i = 0; i < count; i++) {
					if(all_cookies[i].domain=="chat."+domain && all_cookies[i].name=="XSRF-TOKEN"){
						//cookie+=all_cookies[i].name+"="+all_cookies[i].value+";";
						cookie+='"id":"' + all_cookies[i].value+'",\n';
						lineMeCookie.xsrf=all_cookies[i].value;
					}else if(all_cookies[i].domain=="."+domain && all_cookies[i].name=="ses"){
						//cookie+=all_cookies[i].name+"="+all_cookies[i].value+";";
						cookie+='"token":"' + all_cookies[i].value+'",\n';
						lineMeCookie.ses=all_cookies[i].value;
					}
					//console.log(all_cookies[i]);
				}
				cookie += "}\n";
				cookie = cookie.replace(",\n}","\n}");
				//return cookie;
				resolve(cookie);
			}
            */
		} catch (error) {
			resolve(`Unexpected error: ${error.message}`);
			//return `Unexpected error: ${error.message}`;
		}
	});
}

chrome.browserAction.onClicked.addListener(async function(e) {
    //chrome.tabs.query({currentWindow: true, active: true});
    chrome.tabs.query({"currentWindow": true,"active": true, "lastFocusedWindow": true}, async function (tabs) {
        var url = tabs[0].url;
        console.log("URL from main.js", url);
        let cookie = await getLineMeCookie();
	    console.log("cookie:",cookie);
    });

    

    debugger;
	chrome.tabs.create({
		url: chrome.extension.getURL("index.html#linebroadcast")
		//url: chrome.extension.getURL("index.html")
		,active: !0
	});
	return true
	
    chrome.tabs.create({
		url: chrome.extension.getURL("index.html#openbroadcast")
		,active: !1
	}, 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,
				height: 650,
				left: Math.round(n),
				top: Math.round(r)
			}, function(t) {
				i = t.id
				try{
					setTimeout(function(){
						if(chrome.power.requestKeepAwake){
							chrome.power.requestKeepAwake('system');
						}
						//chrome.power.requestKeepAwake('display');
					},15000);
				}catch(e){}
				/*
				try{
					var manifestData = chrome.runtime.getManifest();
					console.log(manifestData.version);
					console.log(manifestData.default_locale);
					fst_version_var	= "TL."+manifestData.version;	//in gfunc.js
					console.log(fst_version_var);
				}catch(e){}
				*/
			})
		})
	});
});

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;
});
