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

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

	window.table = $('.brandnew-to-assigned-tbl').DataTable({
		responsive: false,
		processing: true,
		serverSide: true,
		info: true,
		bAutoWidth: false,
		fixedHeader:true,
		scrollX: true,
		fixedColumns: true,
		fixedColumns: {
			left: 3
		},
		ajax:{
			"url": "{{ route('brand-new-to-assigned-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": "tech_specs" },
			{ "data": "user" },
			{ "data": "title" },
			{ "data": "from_location" },
			{ "data": "assigned_date" },
			{ "data": "age" },
		],
		lengthMenu: [
			[ 50, 100, 200],
			[ '50', '100', '200']
		],
		iDisplayLength: 50,
		fnDrawCallback: function(oSettings) {
		}
	});
}


// 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();

			$('#brandnew-assigned-report-chart').html("");

			if (Object.keys(response.graphData)) {
				$("#data_list").show();
				$('#brandnew-assigned-report-chart').html(response.chartHtml);

				var variable = {
						labels: response.monthNames,
						datasets: [
							{
								label: 'Brand New to Assigned',
								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("brand-new-to-assigned-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();
							}
						}
					};
			} 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('brand-new-to-assigned-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": "user" },
			{ "data": "from_location" },
			{ "data": "assigned_date" },
		],
		lengthMenu: [
			[ 50, 100, 200],
			[ '50', '100', '200']
		],
		iDisplayLength: 50,
		fnDrawCallback: function(oSettings) {}
	});
}



// export report data
function exportReport(name, filename, image)
{
	var form = $("#search-form").serializeObject();
	form.name = name;
	form.filename = filename;
	form.image = image;
    $('.ajax-loader').show();

    $.ajax({
        type: "POST",
        url: "{{ route('brandnew-to-assigned-export') }}",
        data: form,
        xhrFields:{
            responseType: 'blob'
        },
        success: function (result) {
            var blob = new Blob([result]);
            if (window.navigator.msSaveOrOpenBlob)  // IE hack; see http://msdn.microsoft.com/en-us/library/ie/hh779016.aspx
            window.navigator.msSaveBlob(blob, filename + ".xlsx");
            else {
            var a = window.document.createElement("a");
            a.href = window.URL.createObjectURL(blob, { type: "text/plain" });
            a.download = filename + ".xlsx";
            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));
});

// cutton click of singlke export for grap and report
$(document).on('click', '#save-chart-and-list', function (e) {
	e.preventDefault();
	var click = $(this);
	var canvas = document.getElementById('brand-new-to-assigned-chart');

	canvas.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');

        		if (!result || result.error) {
                $('#sync-error').show();
                $('#sync-error-msg').text(result.error);
                return;
            }
				
				    exportReport(name, filename, result.path);
			  },
        error: function(xhr, status, error) {
            $('#sync-error').show();
            $('#sync-error-msg').text(
                "Error: Failed to export chart. Please try again.");
        }
		})
	});
})


$(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());
	});
});

</script>
