app
	.component('appRemolques',{
		templateUrl: './views/remolques/remolques.view.html',
		controller: CtrlRemolques
	});

	CtrlRemolques.$inject = ['$scope','api.service','form.service','alert.service'];

	function CtrlRemolques(scope,api,form,alert) 
	{
		Init = () => 
		{
			scope.spinner = true;
			Paises();
			Remolques();
		}

		Paises = () => 
		{
			api.list('pais').then(res => scope.paises = res.data.paises);
		}

		Remolques = () => 
		{
			scope.spinner = true;
			api.list('remolque').then(res => {
				scope.remolques = res.data.remolques;
			})
			.finally(fin => scope.spinner = false);
		}

		scope.openModal = (index,object = {}) => 
		{
			Clean();

			switch(index)
			{
				case 1:
					scope.modal.edit = false;
					scope.modal.title = "Agregar Remolque";
					form.modal('edit');
				break;
				case 2:
					scope.modal.edit = true;
					scope.modal.title = "Editar Remolque";
					scope.modal.model = angular.copy(object);
					form.modal('edit');
				break;
			}
		}

		scope.save = () => 
		{
			scope.modal.spinner = true;
			scope.modal.fails   = {};

			let promise;

			if(scope.modal.model.id){
				promise = api.update('remolque',scope.modal.model);
			}else{
				promise = api.store('remolque',scope.modal.model);
			}

			promise.then(res => Process(res)).catch(error => ManagerError(error)).finally(fin => scope.modal.spinner = false);
		}

		scope.delete = (remolque) => 
		{
			scope.deleted = remolque;
			alert.confirm("¡Se eliminara el remolque con placa " + remolque.placa + " de la lista de remolques, esta operación es irreversible!",Delete);
		}

		Delete = (remolque) => 
		{
			scope.spinner_delete = true;

			api.delete('remolque',scope.deleted.id).then(res => {
				if(!res.data.success) return ManagerError(res.data.message);
				alert.success(res.data.message);
				Remolques();
			})
			.catch(error => ManagerError(error))
			.finally(fin => scope.spinner_delete = false);
		}

		Process = (res) => 
		{
			if(res.data.fails)
				return scope.modal.fails = res.data.fails;

			if(!res.data.success)
				return alert.warning(res.data.message);
			
			alert.success(res.data.message);
			form.modal('edit',false);
			Remolques();
		}

		ManagerError = (error) => {
			alert.warning(error);
		}

		Clean = () => {
			scope.modal = {model: {},fails: {}};
		}

		Init();
	}