
<script>

var graphLabel;

var pageTheme = window.themeType;

// Define a property with a setter function for window.themeType
Object.defineProperty(window, 'themeType',{
    set: function(newValue) {
		pageTheme = newValue;
		$("#search-form").submit(); 
    }
});

$.fn.serializeObjectCustom = function(){
        var obj = {};

        $.each( this.serializeArray(), function(i,o){
        var n = o.name.replace('[]', ''), v = o.value;

        obj[n] = obj[n] === undefined ? v
            : $.isArray( obj[n] ) ? obj[n].concat( v )
            : [ obj[n], v ];
        });

        return obj;
    };

//set bar options for the graph
var barOptions = {
	responsive: true,
	legend: {
		display: false,
	},
	scales: {
		yAxes: [{
			ticks: {
				maxRotation: 0, // Set the maximum rotation angle
                minRotation: 0,
				beginAtZero:true,
				userCallback: function(label, index, labels) {

				 if (Math.floor(label) === label) {
					 return label;
				 }

			 	}

			}
		}],
		xAxes: [{
			barPercentage: {!! config('graph-settings.barPercentage') !!},
		}]
	},
};


// load graph and table data
function loadPageContent(searchFormObject)
{
	$('.ajax-loader').show();
	$('#sync-error').hide();
	$('#sync-error-msg').text("");

	$.ajax({
		url: searchFormObject.attr('action'),
		method: searchFormObject.attr('method'),
		data: searchFormObject.serializeObject(),
		dataType: "JSON",
		success: function (response) {

			$('.ajax-loader').hide();

			$('#consumption-trends-report-chart').html("");

			if (Object.keys(response.graphData)) {
				$('#consumption-trends-report-chart').html(response.chartHtml);

				var variable = {
						labels: response.monthNames,
						datasets: [
							{
								label: 'Assets',
								backgroundColor: pageTheme == 'dark' ? "{{ config('graph-settings.backgroundColorDark') }}" : "{{ config('graph-settings.backgroundColor') }}",
								pointBorderColor: pageTheme == 'dark' ? "{{ config('graph-settings.pointBorderColorDark') }}" : "{{ config('graph-settings.pointBorderColorDark') }}",
								data: response.graphData
							}
						]
					};

					var canvas = document.getElementById("consumption-trends-chart");
					var ctx = canvas.getContext("2d");
					newChart = new Chart(ctx, {type: 'bar', data: variable, options:barOptions});

					//popup list of selected bar
					canvas.onclick = function(evt) {
						var activePoints = newChart.getElementsAtEvent(evt);
                        
						if (activePoints[0]) {
							var chartData = activePoints[0]['_chart'].config.data;
							var idx = activePoints[0]['_index'];
							graphLabel = chartData.labels[idx];
					
							$('#assets').modal('show');

							if (window.popUpTable == undefined) {
								loadAssetsInPopUp();
							} else {
								window.popUpTable.draw(); 
							}
						}
					};
			}
		},
		error: function (response) {
			$('.ajax-loader').hide();
			$('#sync-error').show();
			$('#sync-error-msg').text("{{ config('graph-settings.graphRequestError') }}");
		}	
	})
}

//show assets of the selected bar in the pop up 
function loadAssetsInPopUp()
{
	window.popUpTable = $('.assets-pop-list').DataTable({
		responsive: false,
		processing: true,
		serverSide: true,
		info: true,
		bAutoWidth: false,
		fixedHeader:true,
		scrollX: true,
		ordering: false, // Disable sorting
		searching: false, // Disable searching
		
		ajax:{
			"url": "{{ route('consumption-trends-data') }}",
			"dataType": "json",
			"type": "POST",
			"data": function( result ) {
				result.form = $('#search-form').serializeObjectCustom();
				result.form.date = graphLabel;
			}
		},
		columns: [
			{ "data": "id" },
			{ "data": "serial_no" },
			{ "data": "asset_type" },
			{ "data": "hardware_standard" },
			{ "data": "tech_specs" },
			{ "data": "asset_status" },
			{ "data": "prev_asset_status" },
			{ "data": "storage_location" },
			{ "data": "storage_country" },
			{ "data": "storage_region" },
			{ "data": "date_assigned" },
		],
		lengthMenu: [
			[ 50, 100, 200],
			[ '50', '100', '200']
		],
		iDisplayLength: 50,
		fnDrawCallback: function(oSettings) {}
	});
}



$("#search-form").on('submit', function(e) {
	e.preventDefault();
	loadPageContent($(this));
});

$(document).ready(function () {
	loadPageContent($("#search-form"));
});

//export xlsx file
$(document).on('click', '.export-chart-btn', function (e) {
	e.preventDefault();
	var click = $(this);
	$('canvas').get(0).toBlob(function(blob) {
		var heading = click.attr('data-name');
		var slug = click.attr('data-slug');
		fd = new FormData();
		fd.append('image', blob);
		fd.append('name', slug);
		$.ajax({  
			type: "POST",  
			url: "/save-image",  
			data: fd,
			processData: false,
			contentType: false,
			success: function(result) {

				var name = click.attr('data-name');
				var filename = click.attr('data-filename');
				var sheetTitle = click.attr('data-sheettitle');
				
				window.location.href='/graph-export?name='+name+'&filename='+filename+'&image='+result.path+'&sheettitle='+sheetTitle
			}
		})
	});
})

</script>