// 読み込んだデータを1行ずつ格納する配列
(()=>{
    var allData = [];
    var now_question = 0;
    var QUIZcsv = "4taku.csv";

    function setQuestion(number){
	var q = allData[number];
	console.log(`number=${number}`);
	document.getElementById("id_question").innerHTML=q.Q
	document.getElementById("id_ChoiceA").innerHTML=q.A
	document.getElementById("id_ChoiceB").innerHTML=q.B
	document.getElementById("id_ChoiceC").innerHTML=q.C;
	document.getElementById("id_ChoiceD").innerHTML=q.D;
	document.getElementById("id_mondaigazo").src="img/"+q.IMG;
	document.getElementById("id_kotae").innerHTML='';
	// document.getElementById("id_miryo").innerHTML='';
    
    //リセット
    document.getElementById("id_pf").innerHTML = '-';
    document.getElementById("id_kotae").innerHTML = '-';
    document.body.style.background = "whire";
    }
    function slide(n) {
	let len = allData.length
	now_question = (len+now_question+n)%len;
	setQuestion(now_question);
    }
    function left() {slide(-1);}
    function right() {slide(1);}

    function answer(e){
	var seikai = allData[now_question].ANS,
	    kaisetsu = allData[now_question].TEXT;
	var kaitou = e.target.value;
	if (kaitou == seikai){
	    document.getElementById("id_pf").innerHTML='正解';
	    document.getElementById("id_kotae").innerHTML=kaisetsu;
	     document.body.style.background = "#ccffff";
	} else {
	    // 不正解の時は背景色を変える
	    document.getElementById("id_pf").innerHTML='不正解 もう一度答えてみよう!';
	    document.getElementById("id_kotae").innerHTML='-';
	     document.body.style.background = "#696969 ";
	}
    }

    function loadCSV(targetFile) {
	fetch(targetFile).			// csvfileをサーバから読み込んで
	    then((resp) => {		// 応答がrespに入るので
		if (resp.ok) return resp.text();	// テキストを返す
	    }).then((txt) => {		// テキストが txt に入るので
		allData = new CSV(txt, {header: true}).parse(); // CSV解析
		setQuestion(0);	// 最初の行のデータを表示
		//console.log(`n=${allData.length}`);
		//console.log(`1=${allData[1].TEXT}`);
	    });;
	
    }
    document.addEventListener("DOMContentLoaded", function() {
	loadCSV(QUIZcsv);
	var checks = document.getElementsByTagName('input'); //すべてのinput
	for (let item of checks) {
	    if (item.getAttribute("name") == "questions") {
		item.addEventListener("click", answer, false);	//answer()関数を呼ぶ
	    }
	}
	document.getElementById("left").addEventListener("click", left);
	document.getElementById("right").addEventListener("click", right);
    }, false);
})();
