$(function() {
	$("#cur_page").inputFilter(function(value) {
		  return /^-?\d*$/.test(value); });
	
	var currentPage = parseInt($("#cur_page").val())
	
	if(currentPage == 1)
		$("#btnPrevPage").hide()
	
	$('#btnPrevPage').click(function() {
		$('#type').val('search');
				
		if((currentPage - 1) < 1)
			return;
			
		$("#cur_page").val(currentPage - 1)
		
		submitForm();
	});
	
	$('#btnNextPage').click(function() {
		$('#type').val('search');
		
		var maximumPage = parseInt($("#max_page").val())
		
		if((currentPage + 1) > maximumPage)
			return;
			
		$("#cur_page").val(currentPage + 1)
			
		submitForm();
	});
	
	$('#dispPage').click(function(){
		$('#type').val('search');
		
		var maximumPage = parseInt($("#max_page").val())
		var selectedPage = parseInt($("#cur_page").val())
		
		if($("#cur_page").val().trim().length == 0)
			return;		
		
		if(selectedPage > maximumPage || selectedPage < 1)
			return;
		
		submitForm();
	})
	
	$('#btnSearch').click(function() {
		$('#type').val('search');
		submitForm();
	});

	$('#from').datepicker({
		// カレンダーの設定
		dateFormat	: 'yy/mm/dd'
	});

	$('#to').datepicker({
		// カレンダーの設定
		dateFormat	: 'yy/mm/dd'
	});

	if($('#from').val() == '') {
		$('#from:text').datepicker().datepicker('setDate','2014/01/01');
	}

	if($('#to').val() == '') {
		$('#to:text').datepicker().datepicker('setDate','today');
	}
	
	$('#btnExport').click(function() {
		var rows = [
			[
				$("#headId").val().trim(),
				$("#headTransactionType").val().trim(),
	            $("#headUserAccount").val().trim(),
	            $("#headUserAccountName").val().trim(),
	            $("#headMoneyIn").val().trim(),
	            $("#headMoneyOut").val().trim(),
	            $("#headCurrency").val().trim(),
	            $("#headFee").val().trim(),
	            $("#headSubmissionRequested").val().trim(),
	            $("#headOperationDate").val().trim(),
	            $("#headReferenceNumber").val().trim(),
	            $("#headMessage").val().trim(),
	            $("#headStatus").val().trim(),
	            $("#headBalance").val().trim()
            ]
		];
		
		$("#exp_progress").show()
		$("#btnSearch").prop({ "disabled" : true })
		$("#btnExport").prop({ "disabled" : true })
		$("#from").prop({ "disabled" : true })
		$("#to").prop({ "disabled" : true })
		
		recursiveFetch({
			"page" : 1,
			"build" : function(result, startRow){				
				result.forEach(function(item, index){
					item = readableTransactionType(item);
					item["id"] = startRow + index;
					item["process_status"] = showTransactionOrigin(item["process_status"]);
					item["account_number"] = item["account_number"].replace(/(<([^>]+)>)/ig, '')
					
					rows.push([
						item["id"],
						item["transaction_type"],
						item["account_number"],
						item["account_name"],
						item["deposit_amount"].replace(/,/g, ""),
						item["withdraw_amount"].replace(/,/g, ""),
						item["currency"],
						item["fee"].replace(/,/g, ""),
						item["transaction_time_string"],
						item["process_time_string"],
						item["transaction_number"],
						item["message"],
						item["status"],
						item["balance"].replace(/,/g, "")
					])
				})
			},
			"release" : function(){				
				$("#exp_progress").hide()
				$("#btnSearch").prop({ "disabled" : false })
				$("#btnExport").prop({ "disabled" : false })
				$("#from").prop({ "disabled" : false })
				$("#to").prop({ "disabled" : false })
				createHyperlinkDownload(rows)
			}
		})
	})
})

function simpleDateFormat(d){
	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);
	
	var formattedDate = `${ye}${mo}${da}`;
	
	return formattedDate;
}

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);
		
	var formattedDates = simpleDateFormat(new Date($("#from").val()))+
		"-"+simpleDateFormat(new Date($("#to").val()));
	
	var link = document.createElement("a");
	link.setAttribute("href", encodedUri);
	link.setAttribute("download", "Transaction_List_"+formattedDates+"_"+$("select[name=currency]").val()+".csv");
	
	document.body.appendChild(link); // Required for FF

	link.click();
}

function recursiveFetch(prop){
	let fd = searchFormData()
	fd.page = prop.page;
	
	pullTxns(fd, {
		"exporting" : true,
		"build" : function(result, pageTotal, startRow){
			if(typeof prop.build !== 'undefined')
				prop.build(result, startRow)
				
			if(prop.page < pageTotal){
				prop.page = prop.page + 1;
				recursiveFetch(prop)
			}else
				prop.release()
		}
	})	
}

function searchFormData(){
	return {
		"cur" : $("select[name=currency]").val(),
		"from" : $("#from").val(),
		"to" : $("#to").val(),
		"page" : 1
	}
}

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();
		txn["message"] = $("#monthlyFeeIndicator").val();
	}else if(txn["transaction_type"] === '2' && txn["type"] == '3'){
		txn["transaction_type"] = $("#cardDepositIndicator").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"] === '11' || txn["transaction_type"] === '12'){
		txn["transaction_type"] = $("#withdrawIndicator").val()+" ("+showWithdrawalStatus(txn["status"])+")";
		txn["status"] = $("#statusComplete").val();
	}else if(txn["transaction_type"] === '11' && txn["status"] == '2'){
		txn["transaction_type"] = $("#feeIndicator").val();
		txn["status"] = $("#statusComplete").val();
		txn["message"] = $("#dormantFeeIndicator").val();
	}
	
	return txn;
}

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 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 pullTxns(formData, config){
	$.ajax({
		"url" : "../api/userTransaction.php",
		"type" : "POST",
		"dataType" : "json",
		"data" : formData,
		"beforeSend" : function(){
			
		},
		"complete" : function(){
			
		},
		"error" : function(data){
			alert("Something Wrong Happened")
		}
	}).done(function(data){
		if(typeof config !== 'undefined')
			config.build(data.result, data["page_total"], data["start_row"])
	})
}
