var currentEditingVehId;
var currentLicenseId;

function RegisterCurrentVehicle() {
	$.post('https://core.vehicles/registerCurrentVehicle', JSON.stringify({}));
}

function closeUI() {
	$('#dmv').css('display', 'none');
	$.post('https://core.vehicles/closeUI', JSON.stringify({}));
}

function showError(msg) {
	$('#errorMsg').text(msg);
	$('#errorModal').modal('show');
}

function showSuccess(msg) {
	$('#successMsg').text(msg);
	$('#successModal').modal('show');
}

function hideAllPages() {
	$('#noLicense').css('display', 'none');
	$('#myVehicles').css('display', 'none');
	$('#manageLicense').css('display', 'none');
	$('#manageCdlLicense').css('display', 'none');
	$('#registerVehiclePage').css('display', 'none');
	$('#registerVehicleManually').css('display', 'none');
	$('#editVehicle').css('display', 'none');
}

function goToPage(page) {
	hideAllPages();
	$('#' + page).css('display', 'block');
}

function createLicense() {
	$.post('https://core.vehicles/createLicense', JSON.stringify({}));
}

function saveLicenseState() {
	var state = $('#licenseState').val();
	var iss = $('#licenseISS').val();
	var exp = $('#licenseEXP').val();

	const licenseJson = JSON.stringify({
		licenseId: currentLicenseId.toString(),
		state: state,
		iss: iss,
		exp: exp
	});

	$.post('https://core.vehicles/editLicenseState', licenseJson);
}

function displayDeleteWarning() {
	$('#deleteModal').modal('show');
}

function DeleteVehicle() {
	$('#deleteModal').modal('hide');
	$.post('https://core.vehicles/deleteVehicle', JSON.stringify({ vehicleId: currentEditingVehId.toString() }));
}

function setupAndDisplayRegisterPage() {
	goToPage('registerVehicleManually');
}

function setupAndDisplayManagePage(reg) {
	veh = reg;
	$('#editPlate').val(veh.LicensePlate);
	$('#editModel').val(veh.ModelName);
	$('#editColour').val(veh.Color);
	$('#editStolen').val(veh.StolenAt ? "true" : "false").trigger('change');
	hideAllPages();
	$('#editVehicle').css('display', 'block');

	currentEditingVehId = veh.VehicleId;
}

function verifyAndRegisterVehicle() {
	var plate = $('#registerPlate').val();
	var model = $('#registerModel').val();
	var colour = $('#registerColour').val();
	var stolen = $('#registerStolen').val();

	$.post('https://core.vehicles/registerVehicleManually', JSON.stringify({
		plate: plate,
		model: model,
		colour: colour,
		stolen: stolen,
	}));
}

function verifyAndSaveVehicle() {
	var plate = $('#editPlate').val();
	var model = $('#editModel').val();
	var colour = $('#editColour').val();
	var stolen = $('#editStolen').val();

	$.post('https://core.vehicles/editVehicle', JSON.stringify({
		vehicleId: currentEditingVehId.toString(), //int to string
		plate: plate,
		colour: colour,
		model: model,
		stolen: stolen,
	}));
}

function isNullOrWhitespace(input) {
	return input === null || input.match(/^\s*$/) !== null;
}

function formatDate(dateobj) {
	var date = new Date(dateobj);
	return date.getUTCFullYear() + "-" +
		("0" + (date.getUTCMonth() + 1)).slice(-2) + "-" +
		("0" + date.getUTCDate()).slice(-2);
}

function setupLightDarkTheme(settings) {
	if (settings.IsDarkModeEnabled) {
		$('#dmv').css('background-color', '#212121');
		$('#dmvcontent').css('background-color', '#212121');
		$('#dmv').addClass('text-white');
		$('.modal-content').addClass('bg-dark text-white');
		$('input').addClass('bg-dark text-white');
	}
	else {
		$('#dmv').css('background-color', 'white');
		$('#dmvcontent').css('background-color', 'white');
		$('#dmv').removeClass('text-white');
		$('.modal-content').removeClass('bg-dark text-white');
		$('input').removeClass('bg-dark text-white');
	}
}

let vehicleList = {};

function setupData(char, vehicles, license, settings) {
	$('#vehiclesTable').empty();
	vehicleList = {};

	//Vehicle List:
	for (i = 0; i < vehicles.length; i++) {
		veh = vehicles[i];
		vehicleList[veh.LicensePlate] = veh;

		stolen = veh.StolenAt ? 'Stolen' : 'Not Stolen';
		if (!veh.DeletedAt) {
			$('#vehiclesTable').append(`<tr><td scope='row' style='vertical-align: middle;'>${veh.LicensePlate}</td><td style='vertical-align: middle;'>${veh.ModelName}</td><td style='vertical-align: middle;'>${veh.Color}</td><td style='vertical-align: middle;'>${stolen}</td><td style='vertical-align: middle;'><button class='btn btn-primary' style='text-align: center; width: 100%; min-height: 10px;' onclick='setupAndDisplayManagePage(vehicleList["${veh.LicensePlate}"])'>Manage</button></td></tr>`);
		}
	}

	//License Page:
	var dob = formatDate(new Date(char.DateOfBirth));
	var iss = formatDate(new Date(license.IssuedAt));
	var exp = formatDate(new Date(license.ExpiresAt));

	$('#licenseText').text('Manage Your Driver\'s License');
	$('#licenseFN').text('FN: ' + char.FirstName);
	$('#licenseLN').text('LN: ' + char.LastName);
	$('#licenseDOB').text('DOB: ' + dob);
	$('#licenseISS').val(iss);
	$('#licenseEXP').val(exp);

	let licenseStatus = "valid";
	if (license.RevokedAt) {
		licenseStatus = "revoked";
	} else if (license.SuspendedAt) {
		licenseStatus = "suspended";
	}

	currentLicenseId = license.LicenseId;

	$('#licenseState').val(licenseStatus).trigger('change');

	//Settings:
	setupLightDarkTheme(settings);

	//General:
	$('#myVehicles').css('display', 'block');
}

$(function () {
	$('.js-example-basic-single').select2(); //initialises custom <select> as NUI/CEF does not support them natively

	window.addEventListener('message', function (event) {
		if (event.data.type == "DMV_OPEN_UI") {
			$('#dmv').css('display', 'block');

			const character = event.data.character ?? {};
			const licenses = Array.isArray(character.Licenses) ? character.Licenses : [];

			// check if the character has a DRIVERS license
			const hasLicense = licenses.some(lic => lic?.LicenseType == "DRIVERS");

			if (hasLicense) {
				hideAllPages();
				$('#sidebarDMV').css('display', 'block');

				const driversLicense = licenses.find(lic => lic?.LicenseType === "DRIVERS") ?? null;
				const vehicles = Array.isArray(character.Vehicles) ? character.Vehicles : [];
				const settings = event.data.settings ?? {};

				setupData(character, vehicles, driversLicense, settings);
			}
			else {
				hideAllPages();
				$('#sidebarDMV').css('display', 'none');
				$('#noLicense').css('display', 'block');
			}
		}
		else if (event.data.type == "DMV_CLOSE_UI") {
			$('#dmv').css('display', 'none');
		}
		else if (event.data.type == "DMV_ERROR_MESSAGE") {
			showError(event.data.msg);
		}
		else if (event.data.type == "DMV_SUCCESS_MESSAGE") {
			showSuccess(event.data.msg);
		}
	});


	$('#registerPlate').bind('copy paste cut', function (e) {
		e.preventDefault(); //disable cut,copy,paste
	});
	$('#editPlate').bind('copy paste cut', function (e) {
		e.preventDefault(); //disable cut,copy,paste
	});
	registerPlate.onkeypress = function (e) {
		if (registerPlate.value.length > 8) return false;
	}
	editPlate.onkeypress = function (e) {
		if (editPlate.value.length > 8) return false;
	}
});