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.view.ViewScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Named;

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

import TO.PrimaryHealthCareCenterTO;
import managedbean.common.ManagedBeanBase;

@Named("ManageHealthCareCenters")
@ViewScoped
public class ManageHealthCareCentersMBean extends ManagedBeanBase implements Serializable {

	private static final long serialVersionUID = 1L;

	private Integer id;
	private String name;
	private String location;
	private PrimaryHealthCareCenterTO primaryHealthCareCenter;
	private LazyDataModel<PrimaryHealthCareCenterTO> lazyDataModelCAPsList;

	public ManageHealthCareCentersMBean() {
	}

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

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

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

	}

	public LazyDataModel<PrimaryHealthCareCenterTO> getlazyDataModelCAPsList() {
		return lazyDataModelCAPsList;
	}

	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 getLocation() {
		return location;
	}

	public void setLocation(String location) {
		this.location = location;
	}

	private void showPrimaryHealthCareCenterData(PrimaryHealthCareCenterTO cap) {
		this.primaryHealthCareCenter = cap;

		if (cap == null) {
			this.id = null;
			this.name = "";
			this.location = "";
		} else {
			this.id = cap.getId();
			this.name = cap.getName();
			this.location = cap.getLocation();
		}
	}

	public PrimaryHealthCareCenterTO getPrimaryHealthCareCenter() {
		return primaryHealthCareCenter;
	}

	public void setPrimaryHealthCareCenter(PrimaryHealthCareCenterTO value) {
		this.primaryHealthCareCenter = value;
	}

	public void onRowEdit(RowEditEvent event) {
		int error = 0;

		String newName = ((PrimaryHealthCareCenterTO) event.getObject()).getName();
		String newLocation = ((PrimaryHealthCareCenterTO) event.getObject()).getLocation();
		
		if (newName == null || newName.trim().length() == 0) {
			this.addFacesMessage(FacesMessage.SEVERITY_WARN, "Nombre no relleno", "Por favor, escriba un nombre para el centro.");
			error++;
		}
		
		if (newLocation == null || newLocation.trim().length() == 0) {
			this.addFacesMessage(FacesMessage.SEVERITY_WARN, "Localización no rellena", "Por favor, escriba una localización.");
			error++;
		}
		
		if (this.getRemoteManagerSystemAdmin().findHealthCareCenterByName(newName) != null) {
			this.addFacesMessage(FacesMessage.SEVERITY_WARN, "CAP ya existente", "El CAP ya se encuentra en la base de datos");
			error++;
		}
		
		if (error == 0) {
			try {
				this.getRemoteManagerSystemAdmin().updateHealthCareCenter(((PrimaryHealthCareCenterTO) event.getObject()).getId(),
						((PrimaryHealthCareCenterTO) event.getObject()).getName(), ((PrimaryHealthCareCenterTO) event.getObject()).getLocation());

				this.showPrimaryHealthCareCenterData(null);

				FacesMessage msg = new FacesMessage("CAP editado", ((PrimaryHealthCareCenterTO) 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", ((PrimaryHealthCareCenterTO) event.getObject()).getName());
		FacesContext.getCurrentInstance().addMessage(null, msg);
	}

	public void deleteDataById(Integer id) throws IOException {
		int error = 0;
		try {
			if (this.getRemoteManagerSystemAdmin().getFamilyDoctorsByCAPCount(id) > 0) {
				this.addFacesMessage(FacesMessage.SEVERITY_ERROR, "No se puede eliminar este CAP",
						"Existen médicos de familia asignados a este CPA, por lo cual no se puede eliminar. Asigne los médicos a otro CAP para proceder a eliminar el CAP a continuación.");
				error++;
			}

			if (error == 0) {
				this.getRemoteManagerSystemAdmin().deleteHealthCareCenter(id);
				this.showPrimaryHealthCareCenterData(null);

				this.addFacesMessage(FacesMessage.SEVERITY_INFO, "El CAP se ha borrado", "Los datos del Centro de Atención Primaria 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 para el centro.");
			error++;
		}

		if (location == null || location.trim().length() == 0) {
			this.addFacesMessage(FacesMessage.SEVERITY_WARN, "Localización no rellena", "Por favor, escriba una localización.");
			error++;
		}

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

		if (error == 0) {
			try {
				this.getRemoteManagerSystemAdmin().insertHealthCareCenter(name, location);
				this.showPrimaryHealthCareCenterData(null);

				this.addFacesMessage(FacesMessage.SEVERITY_INFO, "Los datos se han guardado", "Los datos del Centro de Atención Primaria se han guardado correctamente.");
			} catch (Exception e) {
				this.manageException(e);
			}
		}
	}
}
