package managedbean.systemAdmin;

import java.io.IOException;
import java.io.Serializable;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.view.ViewScoped;
import javax.inject.Named;

import org.primefaces.event.RowEditEvent;
import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;

import TO.MedicalSpecialtyTO;
import managedbean.common.ManagedBeanBase;

@Named("ManageSpecialities")
@ViewScoped
public class ManageSpecialitiesMBean extends ManagedBeanBase implements Serializable {

	private static final long serialVersionUID = 1L;

	private Integer id;
	private String name;
	private String description;
	private MedicalSpecialtyTO medicalSpecialty;
	private LazyDataModel<MedicalSpecialtyTO> lazyDataModelSpecialtiesList;

	public ManageSpecialitiesMBean() {
	}

	@PostConstruct
	public void init() {
		this.lazyDataModelSpecialtiesList = new LazyDataModel<MedicalSpecialtyTO>() {
			private static final long serialVersionUID = 1L;

			@Override
			public List<MedicalSpecialtyTO> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, Object> filters) {
				Long totalRowCount = getRemoteManagerSystemAdmin().getSpecialtiesCount();
				this.setRowCount(totalRowCount.intValue());

				return getRemoteManagerSystemAdmin().listSpecialtiesPaged((first / pageSize), pageSize);
			}
		};

	}

	public LazyDataModel<MedicalSpecialtyTO> getlazyDataModelSpecialtiesList() {
		return lazyDataModelSpecialtiesList;
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	private void showSpecialtyData(MedicalSpecialtyTO ms) {
		this.medicalSpecialty = ms;

		if (ms == null) {
			this.id = null;
			this.name = "";
			this.description = "";
		} else {
			this.id = ms.getId();
			this.name = ms.getName();
			this.description = ms.getDescription();
		}
	}

	public MedicalSpecialtyTO getMedicalSpecialty() {
		return medicalSpecialty;
	}

	public void setMedicalSpecialty(MedicalSpecialtyTO value) {
		this.medicalSpecialty = value;
	}
	
	public void onRowEdit(RowEditEvent event) {
		int error = 0;

		String newName = ((MedicalSpecialtyTO) event.getObject()).getName();
		String newDescription = ((MedicalSpecialtyTO) event.getObject()).getDescription();
		
		if (newName == null || newName.trim().length() == 0) {
			this.addFacesMessage(FacesMessage.SEVERITY_WARN, "Nombre no relleno", "Por favor, escriba un nombre para la especialidad.");
			error++;
		}
		
		if (newDescription == null || newDescription.trim().length() == 0) {
			this.addFacesMessage(FacesMessage.SEVERITY_WARN, "Descripción no rellena", "Por favor, escriba una descripción.");
			error++;
		}
		
		if (this.getRemoteManagerSystemAdmin().findSpecialtyByName(newName) != null) {
			this.addFacesMessage(FacesMessage.SEVERITY_WARN, "Especialidad ya existente", "La especialidad ya se encuentra en la base de datos");
			error++;
		}
		
		if (error == 0) {
			try {
				this.getRemoteManagerSystemAdmin().updateSpecialty(((MedicalSpecialtyTO) event.getObject()).getId(),
						((MedicalSpecialtyTO) event.getObject()).getName(), ((MedicalSpecialtyTO) event.getObject()).getDescription());

				this.showSpecialtyData(null);

				FacesMessage msg = new FacesMessage("Especialidad editada", ((MedicalSpecialtyTO) event.getObject()).getName());
				FacesContext.getCurrentInstance().addMessage(null, msg);
			} catch (Exception e) {
				this.manageException(e);
			}
		}
	}
	
	public void onRowCancel(RowEditEvent event) {
		FacesMessage msg = new FacesMessage("Edición cancelada", ((MedicalSpecialtyTO) event.getObject()).getName());
		FacesContext.getCurrentInstance().addMessage(null, msg);
	}
	
	public void deleteDataById(Integer id) throws IOException {
		int error = 0;
		try {
			if (this.getRemoteManagerMedicalTest().getSpecialistDoctorByMedicalSpecialtyCount(id) > 0) {
				this.addFacesMessage(FacesMessage.SEVERITY_ERROR, "No se puede eliminar esta especialidad",
						"Existen especialistas que tienen asignada esta especialidad médica, por lo cual no puede ser eliminada. Asigne los especialista a otra especialidad para proceder a eliminar la especialidad a continuación.");
				error++;
			}

			if (error == 0) {
				this.getRemoteManagerSystemAdmin().deleteSpecialty(id);
				this.showSpecialtyData(null);

				this.addFacesMessage(FacesMessage.SEVERITY_INFO, "La especialidad se ha borrado", "Los datos de la especialidad se han borrado correctamente.");
			}
		} catch (Exception e) {
			this.manageException(e);
		}
	}
	
	public void insertData() {
		int error = 0;

		if (name == null || name.trim().length() == 0) {
			this.addFacesMessage(FacesMessage.SEVERITY_WARN, "Nombre no relleno", "Por favor, escriba un nombre de especialidad.");
			error++;
		}
		if (description == null || description.trim().length() == 0) {
			this.addFacesMessage(FacesMessage.SEVERITY_WARN, "Descripción no rellena", "Por favor, escriba una descripción.");
			error++;
		}

		if (this.getRemoteManagerSystemAdmin().findSpecialtyByName(name) != null) {
			this.addFacesMessage(FacesMessage.SEVERITY_WARN, "Especialidad ya existente", "La especialidad ya se encuentra en la base de datos");
			error++;
		}

		if (error == 0) {
			try {
				this.getRemoteManagerSystemAdmin().insertSpecialty(name, description);
				this.showSpecialtyData(null);

				this.addFacesMessage(FacesMessage.SEVERITY_INFO, "Los datos se han guardado", "Los datos de la especialidad se han guardado correctamente.");
			} catch (Exception e) {
				this.manageException(e);
			}
		}
	}
}
