app
	.component('appUsuariosPublicos',{
		templateUrl: './views/usuarios-publicos/usuarios-publicos.view.html',
		controller: CtrlUsuariosPublicos
	});

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

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

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

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

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

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

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

			api.delete('usuario_publico',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();
	}