package managedbean.medicalTest;

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

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

import org.primefaces.event.SelectEvent;

import TO.QuestionTO;
import common.QuestionStatus;
import common.UserType;
import managedbean.common.ManagedBeanBase;
import managedbean.common.SessionUtils;

@Named("Questions")
@ViewScoped
public class QuestionsMBean extends ManagedBeanBase implements Serializable {

	private static final long serialVersionUID = 1L;

	private int userID;
	private UserType userType;
	private List<QuestionTO> pendingQuestions;
	private QuestionTO selected;
	private boolean addNewMode;

	public QuestionsMBean() {
	}

	@PostConstruct
	public void init() {
		// Inicialización de variables y propiedades van aquí.
		this.userType = SessionUtils.getUserType();
		this.userID = Integer.valueOf(SessionUtils.getUserId());

		this.addNewMode = false;
		this.selected = null;

		this.loadQuestions();
	}

	public List<QuestionTO> getPendingQuestions() {
		return pendingQuestions;
	}

	public void setPendingQuestions(List<QuestionTO> value) {
		this.pendingQuestions = value;
	}

	/**
	 * Cargará las preguntas enviadas al médico o escritas por el paciente, esto irá en función del tipo de usuario en sesión
	 */
	private void loadQuestions() {
		if (this.userType == UserType.FAMILY_DOCTOR) {
			// Listar las preguntas destinadas a él
			// El método disponible del API básico es referente al doctor
			this.pendingQuestions = getRemoteManagerMedicalTest().listAllPendingQuestions(userID);
		} else if (this.userType == UserType.PATIENT) {
			// Listar las preguntas realiadas por él
			// Para reutilizar la misma view, necesitaremos nuevos métodos para el API de
			// cara a recoger sus preguntas realizadas.
			this.pendingQuestions = getRemoteManagerMedicalTest().listAllMyQuestions(userID);
		}
	}

	public void onSelect(SelectEvent event) {
		this.addNewMode = false;
		this.selected = (QuestionTO) event.getObject();
	}

	public void onUnSelect(SelectEvent event) {
		this.selected = null;
	}

	public void setSelected(QuestionTO selected) {
		this.selected = selected;
	}

	public QuestionTO getSelected() {
		return this.selected;
	}

	public void save() {
		getRemoteManagerMedicalTest().answerQuestion(this.selected.getId(), this.selected.getResponse());
		this.loadQuestions();
		this.addFacesMessage(FacesMessage.SEVERITY_INFO, "Datos guardados", "La respuesta se registrado correctamente en el sistema.");
		this.selected = null;
	}

	public void create() {
		this.addNewMode = true;
		this.selected = new QuestionTO();
		this.selected.setId(-1);
		this.selected.setTitle("");
		this.selected.setMessage("");
	}

	public void addNewQuestion() {
		String result = getRemoteManagerMedicalTest().askQuestion(userID, this.selected.getTitle(), this.selected.getMessage());
		if(result == "ok") {
			this.create();
			this.loadQuestions();
			this.addFacesMessage(FacesMessage.SEVERITY_INFO, "Datos guardados", "La pregunta se registrado correctamente en el sistema.");
		} else {
			this.addFacesMessage(FacesMessage.SEVERITY_ERROR, "Error", result);
		}
		
	}

	public boolean isShowPanelDetail() {
		return this.selected != null && this.addNewMode == false;
	}

	public boolean isPatient() {
		return (this.userType == UserType.PATIENT);
	}

	public boolean isFamilyDoctor() {
		return (this.userType == UserType.FAMILY_DOCTOR);
	}

	public boolean isAddNewMode() {
		return addNewMode;
	}

	public boolean isRespuestaEditable() {
		return (this.userType == UserType.FAMILY_DOCTOR && this.selected != null && this.selected.getStatus() == QuestionStatus.PENDING);
	}

	public void setAddNewMode(boolean addNewMode) {
		this.addNewMode = addNewMode;
	}
}
