var available_printers = null;
var selected_category = null;
var default_printer = null;
var selected_printer = null;
var default_mode = true;

function setup_web_print()
{
	$('#printer_select').on('change', onPrinterSelected);
	showLoading("Cargando información de impresora...");
	default_mode = true;
	selected_printer = null;
	available_printers = null;
	selected_category = null;
	default_printer = null;

	BrowserPrint.getDefaultDevice('printer', function(printer)
	{
		default_printer = printer
		if((printer != null) && (printer.connection != undefined))
		{
			selected_printer = printer;
			var printer_details = $('#printer_details');
			var selected_printer_div = $('#selected_printer');

			selected_printer_div.text("Usando impresora por defecto: " + printer.name);
			hideLoading();
			printer_details.show();

		}
		BrowserPrint.getLocalDevices(function(printers)
			{
				available_printers = printers;
				var sel = document.getElementById("printers");
				var printers_available = false;
				sel.innerHTML = "";
				if (printers != undefined)
				{
					for(var i = 0; i < printers.length; i++)
					{
						if (printers[i].connection == 'usb' || printers[i].connection == 'network')
						{
							var opt = document.createElement("option");
							opt.innerHTML = printers[i].connection + ": " + printers[i].uid;
							opt.value = printers[i].uid;
							sel.appendChild(opt);
							printers_available = true;
						}
					}
				}

				if(!printers_available)
				{
					showErrorMessage("No se encontraron impresoras");
					hideLoading();
					return;
				}
				else if(selected_printer == null)
				{
					default_mode = false;
					changePrinter();
					hideLoading();
				}
			}, undefined, 'printer');
	},
	function(error_response)
	{
		showBrowserPrintNotFound();
	});
};
function showBrowserPrintNotFound()
{
	var os = getOS();
	var download_link = 'https://www.zebra.com/content/dam/zebra_new_ia/en-us/solutions-verticals/product/Software/Printer%20Software/Link-OS/browser-print/';
	if(os == 'Mac OS') {
		download_link = download_link + 'browser-print-1.2.0.3.dmg';
	} else if(os == 'Windows') {
		download_link = download_link + 'zebra-browser-print-setup-1.2.0.3.exe';
	} else {
		download_link = '';
	}
	if(download_link != '') {
		$('#btn-download-zbp').attr('href', download_link).show();
	}
	var message = "Se produjo un error al intentar conectar con su impresora Zebra. Es posible que no tenga Zebra Browser Print instalado o que no esté ejecutándose. Instale Zebra Browser Print, o inicie el servicio de impresión del navegador Zebra, y vuelva a intentarlo.";
	showErrorMessage(message);

};
function sendData()
{
	showLoading("Imprimiendo...");
	checkPrinterStatus( function (text){
		if (text == "Listo para imprimir")
		{
			selected_printer.send($('#print_code').val(), printComplete, printerError);
		}
		else
		{
			printerError(text);
		}
	});
};
function checkPrinterStatus(finishedFunction)
{
	selected_printer.sendThenRead("~HQES",
				function(text){
						var that = this;
						var statuses = new Array();
						var ok = false;
						var is_error = text.charAt(70);
						var media = text.charAt(88);
						var head = text.charAt(87);
						var pause = text.charAt(84);
						// check each flag that prevents printing
						if (is_error == '0')
						{
							ok = true;
							statuses.push("Listo para imprimir");
						}
						if (media == '1')
							statuses.push("Sin papel");
						if (media == '2')
							statuses.push("Cinta térmica agotada");
						if (media == '4')
							statuses.push("Tapa abierta");
						if (media == '8')
							statuses.push("Falla del cortador");
						if (head == '1')
							statuses.push("Sobrecalentamiento del cabezal de impresión");
						if (head == '2')
							statuses.push("Sobrecalentamiento del motor");
						if (head == '4')
							statuses.push("Falla del cabezal de impresión");
						if (head == '8')
							statuses.push("Cabezal de impresión incorrecto");
						if (pause == '1')
							statuses.push("Impresora detenida");
						if ((!ok) && (statuses.Count == 0))
							statuses.push("Error: Error desconocido");
						finishedFunction(statuses.join());
			}, printerError);
};

function showLoading(text)
{
	$('#loading_message').text(text);
	$('#printer_data_loading').show();
	$('#printer_details').hide();
	$('#printer_select').hide();
};
function printComplete()
{
	hideLoading();
        notification({type: "success", content: "Impresión completa"});
        $('#bienes_inventario_imprimir_modal').modal('hide');
}
function hideLoading()
{
	$('#printer_data_loading').hide();
	if(default_mode == true)
	{
		$('#printer_details').show();
	}
	else
	{
		$('#printer_select').show();
	}
};
function changePrinter()
{
	default_mode = false;
	selected_printer = null;
	$('#printer_details').hide();
	if(available_printers == null)
	{
		showLoading("Buscando impresoras...");
		setTimeout(changePrinter, 200);
		return;
	}
	$('#printer_select').show();
	onPrinterSelected();

}
function onPrinterSelected()
{
	selected_printer = available_printers[$('#printers')[0].selectedIndex];
}
function showErrorMessage(text)
{
	$('#main_print').hide();
	$('#error_div').show();
	$('#error_message').html(text);
}
function printerError(text)
{
	showErrorMessage("Ocurrió un error al imprimir. Por favor intente nuevamente." + text);
}
function trySetupAgain()
{
	$('#main_print').show();
	$('#error_div').hide();
	$('#btn-download-zbp').hide();
	setup_web_print();
	//hideLoading();
}