// 例
// https://www.codespeedy.com/change-html5-audio-player-src-file-in-javascript/
function intro() {
    var team = document.getElementById("tm"),
	button = document.getElementById("push"),
	info = document.getElementById("info"),
	myinfo = document.getElementById("myinfo"),
	music = document.getElementById("music"),
	play = document.getElementById("play"),
	msrc = document.getElementById("msrc"),
	climax = document.getElementById("climax");
    var conn, PORT=8804, server = location.hostname;
    server = "wss://www.iekei.org/hayaoshi/"
    var pauseTime, musicinfo;
    function sendmsg(str) {
	conn.send(JSON.stringify({team: team.value, state: str}));
    }
    function stopMusic() {
	if (!music.paused && !pauseTime) {
	    pauseTime = new Date();
	    music.pause();
	}
    }
    function startMusic() {
	pauseTime = null;
	music.play();
    }
    function loadDone(ev) {
	sendmsg("loading done");
	button.disabled = false;
	if (myinfo.textContent.match(/loading/i))
	    if (team.value=="admin") {
		myinfo.textContent = "ヒント="+musicinfo.hint;
	    } else {
		myinfo.textContent += "Done.";
	    }
    }
    music.addEventListener("loadeddata", loadDone, false);
    function initConn() {
	info.textContent = "Volume = "+music.volume;
	try {
	    conn = new WebSocket(server);
	    conn.onopen = function() {};		// Nothing special
	    conn.onerror = function(err) {
		alert('WebSocket failure: ' + err)
	    };
	    conn.onmessage = function(ev) {
		let cmd = ev.data;
		console.log("data: "+cmd);
		if (cmd.match(/src=(.*)/)) {
		    musicinfo = JSON.parse(RegExp.$1);
		    let url = musicinfo.url;
		    music.setAttribute("src", url);
		    myinfo.textContent = "Loading music...";
		    //info.textContent = "Playing "+music.getAttribute("src");
		    music.volume = 0.1;
		    music.load();

		    // if (team.value == "admin") info.textContent += ev.data;
		} else if (ev.data.match(/PING/)) {
		    sendmsg("PONG");
		} else if (ev.data.match(/LOAD: (\d+)\/(\d+)/)) {
		    if (team.value == "admin") {
			var a=parseInt(RegExp.$1), b=parseInt(RegExp.$2);
			// alert(a+"..."+b);
			if (a>=b) {
			    play.textContent = " PLAYxxx ";
			    info.textContent = music.getAttribute("src");
			    play.disabled = false;
			} else {
			    play.textContent = (" PLAY "+a+"/"+b);
			    // play.disabled = true;
			}
		    }
		} else if (ev.data.match(/(PLAY|STOP): ([0-9.]+) ([0-9.]+)/)) {
		    var delay = RegExp.$2*2000,
			ct = parseFloat(RegExp.$3),
			start = (RegExp.$1.match(/PLAY/))
		    delay = Math.round(delay*100)/100;
		    if (delay < 0.1 || delay > 3) delay = 0.1;
		    info.textContent = "PUSH!!!";
		    myinfo.textContent = "Playing position: "+ct+"s, " +
			"my delay: "+delay+"s";
		    if (ct>0) {
			console.log("StartPos="+ct);
			music.currentTime = ct;
		    }
		    setTimeout(function() {
			try {
			    (start) ? startMusic() : stopMusic();
			} catch (err) {
			    alert(err);
			}
		    }, delay);
		    // music.resume().play();
		    // music.play();
		} else if (ev.data.match(/RESET/)) {
		    console.log("Got RESET!!!!!");
		    music.currentTime = 0;
		    stopMusic();
		    //info.textContent = "READY...";
		    info.textContent = musicinfo.hint;
		    button.disabled = false;
		} else if (ev.data.match(new RegExp(team.value))) {
		    // alert(new RegExp(team.value));
		    stopMusic();
		    button.disabled = true;
		} else {
		    stopMusic();
		}
	    };
	    conn.onclose = function(ev) {
		info.textContent = "接続断: 頃合を見てPUSHを押してください。";
		button.disabled = false;
		conn = null;
	    };
	    info.textContent = "Ready...";
	} catch (err) {
	    alert("Socket Creation Error\n\
Firefoxですか? URLウィンドウに about:config と入れて\n\
Search: 窓に websocket と入れて、\n\
network..websocket.allowInsecureFromHTTP\n\
の行をダブルクリックして true に変えてください。\n" + err);
	}
    }
    function push(ev) {
	if (button.disabled) {
	    info.textContent = "今は押せません";
	    return;
	}
	stopMusic();
	if (!conn) {
	    initConn();
	} else if (team.value == "") {
	    alert("Teamに1から6のどれかを入れてね!");
	} else {
	    let ct = music.currentTime;
	    if (music.paused) {
		let now = new Date();
		var elps = (now-pauseTime)/1000;
		ct += elps;
	    }
	    ct = Math.round(ct*100)/100.0;
	    var ji = {team: team.value, state: "PUSH", curtime: ct}
		str = JSON.stringify(ji);
	    myinfo.textContent = "PUSH @ "+ct+"s,"+music.currentTime+", "+elps;
	    conn.send(str);
	}
    }
    document.getElementById("prev").addEventListener("click", function() {
	sendmsg("prev");
    }, false);
    document.getElementById("next").addEventListener("click", function() {
	sendmsg("next");
    }, false);
    document.getElementById("play").addEventListener("click", function() {
	sendmsg("PLAY");
    }, false);
    document.getElementById("stop").addEventListener("click", function() {
	conn.send(JSON.stringify({
	    team: team.value, state: "STOP",
	    curtime: music.currentTime}));
    }, false);
    document.getElementById("reset").addEventListener("click", function() {
	sendmsg("RESET");
    }, false);
    document.getElementById("climax").addEventListener("click", function() {
	sendmsg("SABI");
    }, false);
    function catchClick() {
	// Change the value ::before contents from JS
	// https://shirusu-ni-tarazu.hatenablog.jp/entry/2016/02/04/214451
	info.setAttribute("pre-caution", "");
	info.textContent = "Ready...";
	myinfo.textContent = "";
	music.play(); music.pause();
	info.removeEventListener("click", catchClick);
	info.addEventListener("mousedown", push, false);
    }
    info.addEventListener("click", catchClick, false);
    button.addEventListener("mousedown", push, false);
    initConn();
}
document.addEventListener("DOMContentLoaded", intro, false);
