app
	.component('appPaises',{
		templateUrl: './views/paises/paises.view.html',
		controller: CtrlPaises
	});

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

	function CtrlPaises(scope,api,form,alert) 
	{
		Init = () => 
		{
			scope.spinner = true;
			api.list('pais').then(res => {
				scope.paises = res.data.paises;
			})
			.finally(fin => scope.spinner = false);
		}

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

			switch(index)
			{
				case 1:
					scope.modal.edit = false;
					scope.modal.title = "Agregar País";
					form.modal('edit');
				break;
				case 2:
					scope.modal.edit = true;
					scope.modal.title = "Editar País";
					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('pais',scope.modal.model);
			}else{
				promise = api.store('pais',scope.modal.model);
			}

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

		scope.delete = (pais) => 
		{
			scope.deleted = pais;
			alert.confirm("¡Se eliminara a " + pais.nombre + " de la lista de paises, esta operación es irreversible!",Delete);
		}

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

			api.delete('pais',scope.deleted.id).then(res => {
				if(!res.data.success) return ManagerError(res.data.message);
				alert.success(res.data.message);
				Init();
			})
			.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);
			Init();
		}

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

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

		Init();
	}