document.addEventListener("DOMContentLoaded", ()=>{
    var mainElem = document.getElementById("main"),
	userinput = document.getElementById("user"),
	codeinput = document.getElementById("passcode"),
	noteinput = document.getElementById("note"),
	reply     = document.getElementById("reply");
    var conn, PORT=8889, server = location.hostname||"localhost";
    // server = "localhost";
    var userInfo = {
	"user":		null,
	"tmpkey":	null,
	"skey":		null,
	"stage":	null,
    };
    function clearStorage() {
	for (let key of Object.keys(localStorage)) {
	    if (key.match(/^otp_/)) {
		localStorage.removeItem(key);
		console.log(`localStorage[${key}] cleared`);
	    }
	}
    }
    function replMainHTML(HTMLtext) {
	mainElem.innerHTML = HTMLtext;
    }
    function getMessage(str) {
	console.log(`GET: ${str}`);
	let data = JSON.parse(str);
	if (data.body) {
	    replMainHTML(data.body);
	}
	if (data.tmpkey) {
	    userInfo.tmpkey = data.tmpkey;
	    let codeinput = document.getElementById("passcode");
	    codeinput.disabled = false;
	    codeinput.value = "";
	    codeinput.placeholder = "INPUT passcode";
	    codeinput.focus();
	} else if (data.skey && data.skey > "") {
	    // 認証成功でセッションキーをGET
	    userInfo.skey = data.skey;
	    localStorage.setItem("otp_skey", data.skey);
	    document.getElementById("main").classList.remove("hidden");
	    document.getElementById("auth").classList.add("shrink");
	} else if (data.reply) {
	    // サーバから {"reply": 文字列} が来たらそれを表示
	    reply.innerText = data.reply
	}
    }
    function initConn() {
	try {
	    let url = 'ws://' + server + ':' + PORT + '/';
	    if (location.href.match(/tmp.iekei/))
		url = 'wss://'+location.hostname+'/otpsample';
	    conn = new WebSocket(url);
	    conn.onopen = ()=>{
		// WSソケットが開いたらとりあえずその時の userInfo
		// を送ってみる(skeyが残っていたらログインできるかも)
		conn.send(JSON.stringify(userInfo));
		console.log(`Sending: ${JSON.stringify(userInfo)}`);
	    };
	    conn.onerror = function(err) {
		alert('WebSocket failure: ' + err)
	    };
	    conn.onmessage = function(ev) {
		getMessage(ev.data);
	    };
	    conn.onclose = function(ev) {
		conn = null;
	    };
	} catch (err) {
	    alert(`Socket Creation Error
Firefoxですか? URLウィンドウに about:config と入れて
Search: 窓に websocket と入れて、
network..websocket.allowInsecureFromHTTP
の行をダブルクリックして true に変えてください。\n` + err);
	    return;
	}
	userInfo["user"]	= localStorage.getItem("otp_user");
	userInfo["skey"]	= localStorage.getItem("otp_skey");
    }
    function initListener() {
	function sendUser(e) {
	    let user = userinput.value;
	    localStorage.setItem("otp_user", user)
	    userInfo.user = user;
	    if (user.match(/.+@.+\..+/)) {
		conn.send(JSON.stringify({"user": userInfo.user}));
	    }
	}
	document.getElementById("senduser").addEventListener("click", sendUser);
	userinput.addEventListener("keypress", (e)=>{
	    if (e.key=="Enter") sendUser(e);
	});
	//パスコード入力欄にヒストリがあると邪魔なので消す
	codeinput.value = "";
	function sendPasscode(e) {
	    let code = codeinput.value,
		user = localStorage.getItem("otp_user");
	    if (user.match(/.+@.+\..+/)) {
		conn.send(JSON.stringify({
		    "user": userInfo.user,
		    "passcode": code,
		    "tmpkey": userInfo.tmpkey
		}));
	    }
	}
	document.getElementById("sendcode").addEventListener("click", sendPasscode);
	codeinput.addEventListener("keypress", (e) => {
	    console.log(e.key);
	    if (e.key == "Enter")
		sendPasscode(e);
	});
	noteinput.addEventListener("keypress", (e) => {
	    if (e.key == "Enter" && noteinput.value > "") {
		conn.send(JSON.stringify({"note": noteinput.value}));
		noteinput.value = ""	// 送信したら消す
	    }
	});
	document.getElementById("clear").addEventListener(
	    "click", clearStorage);
    }
    initConn();
    initListener();
});
