
<style>
#assets .dataTables_scrollHead {
    top: 0!important;
}
</style>
<script>

var graphLabel;
var selectedAssetTypeBar;

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 table data
function loadData()
{
	$("#data_list").show();

	window.table = $('.assets-created-tbl').DataTable({
		responsive: false,
		processing: true,
		serverSide: true,
		info: true,
		bAutoWidth: false,
		fixedHeader:true,
		scrollX: true,
		fixedColumns: true,
		fixedColumns: {
			left: 3
		},
		ajax:{
			"url": "{{ route('assets-created-data') }}",
			"dataType": "json",
			"type": "POST",
			"data": function( result ) {
				result.form = $('#search-form').serializeObjectCustom();
			},
			error: function(xhr, errorType, exception) {
				$('.ajax-loader').hide();
				$('#sync-error').show();
				$('#sync-error-msg').text("{{ config('graph-settings.graphRequestError') }}");
        	}
		},
		columns: [
			{ "data": "id" },
			{ "data": "asset_tag" },
			{ "data": "serial_no" },
			{ "data": "asset_type" },
			{ "data": "hardware_standard" },
			{ "data": "technical_specs" },
			{ "data": "user_location" },
			{ "data": "created_at" },
		],
		lengthMenu: [
			[ 50, 100, 200],
			[ '50', '100', '200']
		],
		iDisplayLength: 50,
		fnDrawCallback: function(oSettings) {
			if (oSettings.fnRecordsTotal() == 0) {
				$("#export-csv").hide();
			} else {
				$("#export-csv").show();
			}
		}
	});
}


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

    if (window.table == undefined) {
			loadData();
	} else {
		window.table.draw();
	}

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

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

			$('#assets-created-report-chart').html("");

            if (Object.keys(response.assetTypes)) {
				$("#data_list").show();
				$('#assets-created-report-chart').html(response.chartHtml);

                var myNewChart = [];
				var hasResults = false;
				$('.assets-graph-container').hide();


                $.each(response.assetTypes, function(index, element) {
					hasResults = true;;
                    var dynamicVariableName = 'variable_' + element.id;
                    this[dynamicVariableName] = {
						labels: response.monthNames,
						datasets: [
							{
								label: element.name,
								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[element.slug]
							}
						]
					};

                    var canvas = document.getElementById("barChart_" + element.slug);
                    var ctx2 = canvas.getContext("2d");
                    myNewChart[element.slug] = new Chart(ctx2, {type: 'bar', data: this[dynamicVariableName], options:barOptions});

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

							if (window.popUpTable == undefined) {
								loadAssetsInPopUp();
							} else {
								window.popUpTable.draw();
							}
						}
					};
                
                });

				if (hasResults) {
					$('.assets-graph-container').show();
				}

				
			} else {
				$("#data_list").hide();
			}
		},
		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('assets-created-data') }}",
			"dataType": "json",
			"type": "POST",
			"data": function( result ) {
				result.form = $('#search-form').serializeObjectCustom();
				result.form.date = graphLabel;
				result.form.selectedAssetTypeBar = selectedAssetTypeBar;
			}
		},
		columns: [
			{ "data": "id" },
			{ "data": "asset_tag" },
			{ "data": "serial_no" },
			{ "data": "asset_type" },
			{ "data": "hardware_standard" },
			{ "data": "technical_specs" },
			{ "data": "user_location" },
			{ "data": "created_at" },
		],
		lengthMenu: [
			[ 50, 100, 200],
			[ '50', '100', '200']
		],
		iDisplayLength: 50,
		fnDrawCallback: function(oSettings) {}
	});
}

$('#export-csv').on('click', function (e) {
        e.preventDefault();
        $('.ajax-loader').show();
		$.ajax({
            type: "POST",
            url: "{{ route('assets-created-export') }}",
            data: $('#search-form').serializeObjectCustom(),
            dataType: 'text',
            success: function (result) {
                var blob = new Blob([result]);
                var filename = "assets-created-report.csv"
                if (window.navigator.msSaveOrOpenBlob)  // IE hack; see http://msdn.microsoft.com/en-us/library/ie/hh779016.aspx
                    window.navigator.msSaveBlob(blob, filename);
                else {
                    var a = window.document.createElement("a");
                    a.href = window.URL.createObjectURL(blob, { type: "text/plain" });
                    a.download = filename;
                    document.body.appendChild(a);
                    a.click();  // IE: "Access is denied"; see: https://connect.microsoft.com/IE/feedback/details/797361/ie-10-treats-blob-url-as-cross-origin-and-denies-access
                    document.body.removeChild(a);
                }
                $('.ajax-loader').hide();
            }
        })
    });




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


$(document).ready(function () {

	loadPageContent($("#search-form"));

	// Data table column toggle
	$('span.col-toggle').on('click', function (e) {
		e.preventDefault();
		$(this).toggleClass('col-hidden');
		// Get the column API object
		var column = window.table.column($(this).attr('data-column'));
		// Toggle the visibility
		column.visible(!column.visible());
	});
});

//export xlsx file
$(document).on('click', '.export-chart-btn', function (e) {
	e.preventDefault();
	$('.ajax-loader-graph-export').show();
	var click = $(this);
	$(this).closest('.canvas-container').find('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) {
				$('.ajax-loader-graph-export').hide();
				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>
