$(function(){
	$('#btnSearch').click(function() {
		$('#s_type').val('search');
		submitForm('searchForm');
	});
	
	$("#btnBack").click(function(){
		var currentUrl = window.location.href; 
		var modifiedBase = currentUrl.substring(0, currentUrl.lastIndexOf("/") + 1)
		
		window.location.href = modifiedBase+"account_edit?detail_account="+$("#detail_account").val()
	})
	
	$('#s_from').datepicker({
		// カレンダーの設定
		dateFormat	: 'yy/mm/dd'
	});

	$('#s_to').datepicker({
		// カレンダーの設定
		dateFormat	: 'yy/mm/dd'
	});
	
	$('#btnSearchToday').click(function() {
		$('#s_type').val('search');
		$('#s_from:text').datepicker().datepicker('setDate', 'today');
		$('#s_to:text').datepicker().datepicker('setDate', 'today');
		$('#s_email').val('');
		$('#s_account').val('');
		$('#transaction_number').val('');
		$('#transaction_type').val('');
		$('#s_currency').val('');
		submitForm('searchForm');
	});
	
	var currentSToVal = new Date($('#s_to').val())
	var currentSToMonth = currentSToVal.getMonth() + 1
	var currentSToYear = currentSToVal.getFullYear()
	var currentSToDate = currentSToVal.getDate()
	if(month < 9) {
		currentSToMonth = "0" + currentSToMonth
	}

	if(date < 9) {
		currentSToDate = "0" + currentSToDate
	}

	if($('#s_from').val() == '') {
		var nowDate	= new Date();
		nowDate.setMonth(nowDate.getMonth() - 2);
		var month	= nowDate.getMonth();
		var year	= nowDate.getFullYear();
		var date 	= nowDate.getDate();

		month = month + 1;

		if(month < 9) {
			month = "0" + month
		}

		if(date < 9) {
			date = "0" + date
		}

		var thisStr = year + '/' + month + '/' + '01';
		$('#s_from:text').datepicker().datepicker('setDate', thisStr);
	}
	
	var setSto = currentSToYear + '/' + currentSToMonth + '/' + currentSToDate;
	
	if($('#s_to').val() == '') {
		$('#s_to:text').datepicker().datepicker('setDate','today');
	} else {
		$('#s_to:text').datepicker().datepicker('setDate', setSto);
	}
		
	$(".cur-table").each(function(i, e){
		var fd = searchFormData()
		fd.cur = $(this).find("[type=hidden]").val()
		
		$("#prev_"+fd.cur).click(function(e){
			paginate("prev", $(this).attr("focused-cur"))
		})
		
		$("#next_"+fd.cur).click(function(e){
			paginate("next", $(this).attr("focused-cur"))
		})
		
		$("#express_"+fd.cur).click(function(e){
			paginate("express", $(this).attr("focused-cur"))
		})
		
		pullTxns(fd, {
			"tableBody" : $("#transaction_body_"+fd.cur)
		})
	})
	
	$("#btnExport").click(function() {
		var rows = [
			[
				$("#headTransactionType").val().trim(),
	            $("#headUserAccount").val().trim(),
	            $("#headUserAccountName").val().trim(),
	            $("#headCurrency").val().trim(),
	            $("#headDepositAmount").val().trim(),
	            $("#headWithdrawalAmount").val().trim(),
	            $("#headFee").val().trim(),
	            $("#headDateRequested").val().trim(),
	            $("#headProcessngDate").val().trim(),
	            $("#headTransactionNumber").val().trim(),
	            $("#headMessage").val().trim(),
	            $("#headType").val().trim(),
	            $("#headCurrentStatus").val().trim(),
	            $("#headBalance").val().trim()
            ]
		];
		
		$("#file_exporter_prog").show()
		
		recursiveFetch({
			"start" : 0,
			"page" : 1,
			"build" : function(result){
				result.forEach(function(item, index){
					item = readableTransactionType(item);
					item["process_status"] = showTransactionOrigin(item["process_status"]);
					item["account_number"] = item["account_number"].replace(/(<([^>]+)>)/ig, '')
					
					rows.push([
						item["transaction_type"],
						item["account_number"],
						item["account_name"],
						item["currency"],
						item["deposit_amount"].replace(/,/g, ""),
						item["withdraw_amount"].replace(/,/g, ""),
						item["fee"].replace(/,/g, ""),
						item["transaction_time_string"],
						item["process_time_string"],
						item["transaction_number"],
						item["message"],
						item["type"],
						item["process_status"],
						item["balance"].replace(/,/g, "")
					])
				})
			},
			"release" : function(){
				$("#file_exporter_prog").hide()
				createHyperlinkDownload(rows)
			}
		})
	});
})

function recursiveFetch(prop){
	let currencies = [];
	
	$(".cur-table").each(function(i, e){
		currencies.push($(this).find("[type=hidden]").val())
	})
	
	if(currencies.length != 0){
		var fd = searchFormData();
		fd.cur = currencies[prop.start];
		fd.page = prop.page;
		
		let totalPage = $("#total_page_"+fd.cur).val()
		
		pullTxns(fd, {
			"exporting" : true,
			"build" : function(result){
				if(typeof prop.build !== 'undefined')
					prop.build(result)
				
				if(totalPage > prop.page){
					prop.page = prop.page + 1;
					recursiveFetch(prop)
				}else if(prop.start < currencies.length){
					prop.page = 1;
					prop.start = prop.start + 1;
					recursiveFetch(prop)
				}else
					prop.release()
			}
		})
	}
}

function createHyperlinkDownload(rows){
	let csvContent = "data:text/csv;charset=utf-8,";
	
	rows.forEach(function(rowArray) {
		let row = rowArray.join(",");
		csvContent += "\ufeff" + row + "\r\n";
	});
	
	var encodedUri = encodeURI(csvContent);
	
	let d = new Date();
	let ye = new Intl.DateTimeFormat('en', { year: 'numeric' }).format(d);
	let mo = new Intl.DateTimeFormat('en', { month: '2-digit' }).format(d);
	let da = new Intl.DateTimeFormat('en', { day: '2-digit' }).format(d);
	let ho = new Intl.DateTimeFormat('en', { hour: '2-digit', hour12 : false}).format(d);
	let mi = new Intl.DateTimeFormat('en', { minute: '2-digit' }).format(d);
	let se = new Intl.DateTimeFormat('en', { second: '2-digit' }).format(d);
	
	var formattedDate = `${ye}${mo}${da}${ho}${mi}${se}`;
	
	var link = document.createElement("a");
	link.setAttribute("href", encodedUri);
	link.setAttribute("download", `Trans_List_${formattedDate}.csv`);
	
	document.body.appendChild(link); // Required for FF

	link.click();
}

function paginate(direction, focusedCur){
	var fd = searchFormData()
	
	var currentPage = parseInt($("#crnt_page_"+focusedCur).val())
	var inputtedPage = parseInt($("#move_page_high_"+focusedCur).val())
	var totalPage = parseInt($("#total_page_"+focusedCur).val())
	var changes = false;
	
	switch(direction){
		case "prev":
			if(currentPage > 1){
				fd.page = currentPage - 1;
				changes = true;
			}
			break;
		case "next":
			if(currentPage < totalPage){
				fd.page = currentPage + 1;
				changes = true;
			}
			break;
		case "express":
			if(inputtedPage >= 1 && inputtedPage <= totalPage){
				fd.page = inputtedPage;
				changes = true;
			}
			break;
	}
	
	if(changes){		
		fd.cur = focusedCur;
		
		$("#crnt_page_"+focusedCur).val(fd.page)
		$("#currentPageNum_"+focusedCur).html(fd.page)
		$("#move_page_high_"+focusedCur).val(fd.page)
		
		pullTxns(fd, {
			"tableBody" : $("#transaction_body_"+focusedCur)
		})
	}
}

function searchFormData(){
	return {
		"detailAccount" : $("#detail_account").val(),
		"from" : $("#s_from").val(),
		"to" : $("#s_to").val(),
		"txnNum" : $("#transaction_num").val(),
		"email" : $("#s_email").val(),
		"cur" : $("#s_currency").val(),
		"userAccount" : $("#s_account").val(),
		"txnType" : $("#transaction_type").val(),
		"page" : 1
	}
}

function showTransactionOrigin(type){
	var origin;
	
	switch(type){
		case '0':
			origin = "User";
			break;
		case '1':
			origin = "Admin";
			break;
		case '2':
			origin = "API";
			break;
		case '3':
			origin = "Batch";
			break;
	}
	
	return origin;
}

function showWithdrawalStatus(status){
	const withdrawalStatus = [
		$("#statusApply").val(),
		$("#statusRemittanceAccepted").val(),
		$("#statusRemittanceAlready").val(),
		$("#statusDeficiencyChecking").val(),
		$("#statusRefund").val(),
		$("#statusCancellation").val(),
		$("#statusCancel").val()
	]
	
	var transactionStatus;
	
	withdrawalStatus.forEach(function(item, index){
		if(status == index)
			transactionStatus = item;
	})
	
	return transactionStatus;
}

function readableTransactionType(txn){
	if(txn["transaction_type"] === '1'){
		txn["transaction_type"] = $("#depositIndicator").val();
		txn["status"] = $("#statusComplete").val();
	}else if(txn["transaction_type"] === '2' && txn["type"] == '0'){
		txn["transaction_type"] = $("#withdrawIndicator").val()+" ("+showWithdrawalStatus(txn["status"])+")";
		txn["status"] = showWithdrawalStatus(txn["status"]);
	}else if(txn["transaction_type"] === '2' && txn["type"] == '1'){
		txn["transaction_type"] = $("#feeIndicator").val();
		txn["status"] = $("#statusComplete").val();
	}else if(txn["transaction_type"] === '2' && txn["type"] == '3'){
		txn["transaction_type"] = $("#internalTransferTrash").val();
		txn["status"] = $("statusComplete").val();
	}else if(txn["transaction_type"] === '3' || txn["transaction_type"] === '4'){
		txn["transaction_type"] = $("#exchangeIndicator").val();
		txn["status"] = $("#statusComplete").val();
	}else if(txn["transaction_type"] === '5' || txn["transaction_type"] === '6'){
		txn["transaction_type"] = $("#internalTransfer").val();
		txn["status"] = $("#statusComplete").val();
	}else if(txn["transaction_type"] === '7' || txn["transaction_type"] === '8'){
		txn["transaction_type"] = $("#requestIndicator").val();
		txn["status"] = $("#statusComplete").val();
	}else if(txn["transaction_type"] === '9' || txn["transaction_type"] === '10' || txn["transaction_type"] === '12'){
		txn["transaction_type"] = $("#withdrawIndicator").val()+" ("+showWithdrawalStatus(txn["status"])+")";
		txn["status"] = $("#statusComplete").val();
	}else if(txn["transaction_type"] === '11'){
		txn["transaction_type"] = $("#feeIndicator").val();
		txn["status"] = $("#statusComplete").val();
	}
	
	return txn;
}

function createTransactionRow(txn){
	var row = '<tr>'+
		'<td class="c">{row_num}</td>'+
		'<td class="c">{transaction_type}</td>'+
		'<td class="c">{account_number}</td>'+
		'<td class="l">{account_name}</td>'+
		'<td class="r">{deposit_amount}</td>'+
		'<td class="r">{withdraw_amount}</td>'+
		'<td class="r">{fee}</td>'+
		'<td>{transaction_time_string}</td>'+
		'<td>{process_time_string}</td>'+
		'<td class="c">{transaction_number}</td>'+
		'<td class="l">{message}</td>'+
		'<td class="c">{process_status}</td>'+
		'<td class="c">{status}</td>'+
		'<td class="r">{balance}</td>'+
		'</tr>';
	
	var matches = row.match(/\{([A-Za-z0-9_]+)\}/g)
	
	matches.forEach(function(item, index){
		var mdata = item.replace(new RegExp("(\\{|\\})", "g"), '')
		
		switch(mdata){
			case "balance":
			case "deposit_amount":
			case "withdraw_amount":
			case "fee":
				if(txn[mdata].trim().length != 0)
					txn[mdata] = txn["currency"]+" "+txn[mdata];
				break;
			case "transaction_type":
				txn = readableTransactionType(txn)
				break;
			case "process_status":
				txn[mdata] = showTransactionOrigin(txn[mdata]);
				break;
		}
			
		row = row.replace(item, txn[mdata])
	})
	
	return row;
}

function pullTxns(formData, config){
	$.ajax({
		"url" : "../api/transaction_history.php",
		"type" : "POST",
		"dataType" : "json",
		"crossDomain" : true,
		"data" : formData,
		"beforeSend" : function(){
			if(typeof config.tableBody !== 'undefined'){
				config.tableBody.empty()
				$("#elapsed_time_"+formData.cur).html('')
				
				$("#move_page_high_"+formData.cur).prop({ "disabled" : true })
				$("#express_"+formData.cur).prop({ "disabled" : true })
				$("#prev_"+formData.cur).prop({ "disabled" : true })
				$("#next_"+formData.cur).prop({ "disabled" : true })
				
				config.tableBody.append('<td colspan="14">'+$("#progressIndicator").val()+'</td>')
			}
		},
		"complete" : function(){
			if(typeof config.tableBody != 'undefined'){
				$("#move_page_high_"+formData.cur).prop({ "disabled" : false })
				$("#express_"+formData.cur).prop({ "disabled" : false })
				$("#prev_"+formData.cur).prop({ "disabled" : false })
				$("#next_"+formData.cur).prop({ "disabled" : false })
			}
		},
		"error" : function(data){
			alert("Something Wrong Happened ["+formData.cur+"]")
		}
	}).done(function(data){
		if(typeof config.tableBody !== 'undefined'){
			$("#rowCount_"+formData.cur).html(data["row_count"])
			$("#currentPageNum_"+formData.cur).html(data["current_page"])
			$("#pageTotal_"+formData.cur).html(data["total_page"])
			
			// hidden inputs
			$("#crnt_page_"+formData.cur).val(data["current_page"])
			$("#total_page_"+formData.cur).val(data["total_page"])
			
			// page express
			$("#move_page_high_"+formData.cur).val(data["current_page"])
			
			$("#elapsed_time_"+formData.cur).html(parseFloat(data["elapsed_time"]).toFixed(3))
			
			config.tableBody.empty()
			
			if(data.result.length > 0){
				data.result.forEach(function(item, index){
					item["row_num"] = data["start_row"] + index;
					config.tableBody.append(createTransactionRow(item))
				})
			}else
				config.tableBody.append('<td colspan="14">'+$("#noResultsFound").val()+'</td>')
		}else{
			if(typeof config.exporting !== 'undefined'){
				config.build(data.result)
			}	
		}
	})
}