/* How to create shochu-csv
  https://www.mext.go.jp/b_menu/toukei/mext_01087.html
  nkf -Sw /tmp/221222-mxt-mxt_chousa01-1000011635_2.csv \
    | awk -F,  '$1 ~ /^[BC]/ {printf("%s,%s,%s\n",$1,substr($2,1,2),$3) }' \
    | awk -F, '$2>1 && $2<=7 || $2==15 {print}' > out
*/
window.addEventListener(
"DOMContentLoaded",
async function () {
    var schools, filterbox, nameptn, prefradio;
    var schoolcsv = "./shochu-tohoku-niigata.csv";
    var prefcsv = "./pref.csv", prefs={};
    var getapp = "./getapp.rb";
    var requiredNames = [
	"schoolname", "name", "hiraname", "fm", "birthday", "grade",
	"seatnum", "pname", "address", "phone", "email",
	"interview", "motive", "interest", "issues", "selfintro"
    ];
    var today = new Date(),
	year = today.getFullYear(),
	youngest = 11, oldest = youngest+4;
    var isOlderJS = false;
    async function loadurl(url) {
	// return await fetch(url).then((resp) => {return resp.text()});
	return new CSV(await fetch(url).then((resp) => {return resp.text()}),
		       {header: true}).parse();;
    }
    // https://developer.mozilla.org/ja/docs/Web/API/SubtleCrypto/digest
    async function digestMessage(message) {
	// encode as (utf-8) Uint8Array
	const msgUint8 = new TextEncoder().encode(message);
        // hash the message
	const hashBuffer = await crypto.subtle.digest('SHA-256', msgUint8);
        // convert buffer to byte array
	const hashArray = Array.from(new Uint8Array(hashBuffer));
	// convert bytes to hex string
	const hashHex = hashArray.map(
	    b => b.toString(16).padStart(2, '0')).join('');
	return hashHex;
    }
    // alert(await digestMessage("foo"));
    async function checkMid() {
	var email, mid, dig;
	if (document.URL.match(/\?email=(.*?)\+mid=(.*)/)) {
	    email = unescape(RegExp.$1),
	    mid   = RegExp.$2,
	    dig   = (await digestMessage(email)).substr(0, 10);
	}
	// alert(dig.substr(0,10));
	console.log("email="+email);
	console.log("dig="+dig);
	console.log("mid="+mid);
	if (email && dig && dig == mid) {
	    document.getElementById("email").value = email;
	    document.getElementById("email2").textContent = email;
	    // ei.disabled = true;
	} else {
	    // alert("no match");
	    // window.location.replace("getapp.rb");
	    window.location.href = getapp ;
	}
    }
    function validate(ev) {
	// Check only if it is not empty
	var nEmpty = 0, firstEmpty;
	let f = document.forms[0];
	for (let rn of requiredNames) {
	    let e = f.querySelector('*[name="' + rn + '"]');
	    if (e.value != null && e.value == "") {
		ev.preventDefault(); // Cancel SUBMIT!
		e.style.background = "pink";
		nEmpty++;
		if (!firstEmpty) firstEmpty = e;
	    } else {
		e.style.background = "";
	    }
	}
	if (nEmpty > 0) {
	    if (firstEmpty.scrollIntoView) {
		let option = {behavior: "smooth"};
		if (!isOlderJS) option.block = "center";
		try {	// Scroll to last updated row
		    firstEmpty.scrollIntoView(option);
		    alert("空欄を埋めてください");
		} catch (e1) {}
	    }
	    return true;
	}
    }
    function setgrade(ev) {
	var b = ev.target.value,
	    youngest = 11, oldest = youngest+4;
	if (b.match(/(\d\d\d\d)[-/](\d\d)[-/](\d\d)/)) {
	    let y = RegExp.$1, m = RegExp.$2, d = RegExp.$3,
		by = parseInt(y),
		bw = document.getElementById("birthwarn"),
		past = year - by, e;
	    if (m+"-"+d <= "04-01") past++;
	    if (past < youngest || past > oldest) {
		bw.textContent = "小5から中3までの方のみです。";
		ev.target.style.background = "pink";
		return;
	    }
	    bw.textContent = "";
	    ev.target.style.background = null;
	    e = document.forms[0].querySelectorAll(
		'select[name="grade"] option');
	    e[past-youngest].selected = true;
	}
    }
    function init() {
	isOlderJS = !("insertAdjacentElement" in document.body);
	checkMid();
	// load
	fetch(schoolcsv).then((resp) => {
	    return resp.text().then((text) => {
		gentable(new CSV(text, {header: true}).parse());
	    })})
	fetch(prefcsv).then((resp) => {
	    return resp.text().then((text) => {
		for (let prow of new CSV(text, {header: true}).parse())
		    prefs[prow["pn"]] = prow["pref"];
	    })})
	filterbox = document.getElementById("nameptn");
	filterbox.addEventListener("input", (ev) => {schoolfilter(ev)});
	prefradio = document.forms[0].pref; // get name="pref" nodeList
	for (let i of document.querySelectorAll('input[name="pref"]')) {
	    i.addEventListener("input", (ev) => {schoolfilter(ev)});
	}
	nameptn = document.getElementById("nameptn");
	let birthday = document.forms[0].birthday;
	if (birthday) {
	    birthday.addEventListener('input', setgrade, false);
	    birthday.setAttribute("min", `${year-oldest}-04-02`);
	    birthday.setAttribute("max", `${year-youngest+1}-04-01`);
	    birthday.setAttribute("value", `${year-youngest}-04-02`);
	}
	// Set validaters
	for (let i of document.querySelectorAll('input[type="submit"]')) {
	    i.addEventListener("click", validate, false);
	}
    }
    function schoolfilter(e) {
	var str = nameptn.value,
	    tbl = document.getElementById("schools"),
	    pref= prefradio.value;
	let n=0, i=0, flag;
	reg = RegExp(str)
	console.log("nameptn=["+nameptn+"]");
	console.log("str=["+str+"]");
	for (let row of tbl.querySelectorAll("tr")) {
	    let lb = row.querySelector("label");
	    flag = "";
	    /* if (lb.textContent.match(reg)) {
		console.log(lb.textContent);
		row.setAttribute("class", "match");
		n++;
		} else */
	    if (str > "" && lb.textContent.includes(str)) {
		// console.log(lb.textContent);
		if (pref == schools[i]["prefcode"] || pref == "") {
		    flag = "match";
		    n++;
		}
	    } else {
		// row.setAttribute("class", "");
	    }
	    row.setAttribute("class", flag);
	    i++;
	}
	console.log("n="+n+", "+tbl.childNodes.length);
	
    }
    function updateSchool(e) {
	// alert("YES");
	var nm = document.getElementById("schoolname"),
	    id = document.getElementById("schoolid");
	// nm.value = document.forms[0].school.value;
	nm.value = e.target.nextSibling.textContent;
	id.value = e.target.value;
    }
    function gentable(csv) {
	schools = csv;
	var sctbl = document.getElementById("schools");
	var nSchl = 0;
	for (let s of schools) {
	    // Generate <input type="radio" name="school"> for all schools
	    let row = document.createElement("tr"),
		col = document.createElement("td"),
		code = s["code"],
		pref = s["prefcode"],
		schl = s["schoolname"],
		labl = document.createElement("label"),
		ssel = document.createElement("input");
	    ssel.setAttribute("type", "radio");
	    ssel.setAttribute("name", "school");
	    ssel.setAttribute("value", code);
	    ssel.setAttribute("class", pref);
	    ssel.addEventListener("change", updateSchool, false);
	    labl.appendChild(ssel);
	    labl.appendChild(document.createTextNode(schl));
	    col.appendChild(labl);
	    row.appendChild(col);
	    sctbl.appendChild(row);
	    nSchl++;
	}
	console.log("done "+nSchl);
    }
    init();
}, false);
