package managedbean.visit;

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

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

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

import TO.VisitTO;
import managedbean.common.ManagedBeanBase;
import managedbean.common.SessionUtils;

@Named("VisitList")
@ViewScoped
public class VisitListMBean extends ManagedBeanBase implements Serializable {

	private static final long serialVersionUID = 1L;

	private int familyDoctorId;
	private String familyDoctorDisplayName;
	private LazyDataModel<VisitTO> lazyDataModelVisitList;
	private LocalDate selectedDate;

	public VisitListMBean() {
	}

	@PostConstruct
	public void init() {
		// El usuario actual es un medico de familia, recuperamos su Id de la sessión actual
		this.familyDoctorId = Integer.valueOf(SessionUtils.getUserId());
		this.familyDoctorDisplayName = SessionUtils.getUserDisplayName();
		
		this.selectedDate = LocalDate.now();

		this.lazyDataModelVisitList = new LazyDataModel<VisitTO>() {
			private static final long serialVersionUID = 1L;

			@Override
			public List<VisitTO> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, Object> filters) {
				Long totalRowCount = getRemoteManagerVisit().getScheduledVisitsCount(familyDoctorId, selectedDate);
				this.setRowCount(totalRowCount.intValue());

				return getRemoteManagerVisit().listAllScheduledVisitsPaged(familyDoctorId, selectedDate, (first / pageSize), pageSize);
			}
		};
	}

	public LazyDataModel<VisitTO> getLazyDataModelVisitList() {
		return lazyDataModelVisitList;
	}
	
	public void showData() {
	}
	
	public void showVisit(Integer visitId) throws IOException {
		FacesContext ctx = FacesContext.getCurrentInstance();
	    ctx.getExternalContext().redirect(String.format("VisitView.xhtml?id=%d&fromPage=%s", visitId, ctx.getViewRoot().getViewId()));
	}

	public void editVisit(Integer visitId) throws IOException {
		FacesContext ctx = FacesContext.getCurrentInstance();
	    ctx.getExternalContext().redirect(String.format("UpdateVisit.xhtml?id=%d&fromPage=%s", visitId, ctx.getViewRoot().getViewId()));
	}

	public LocalDate getSelectedDate() {
		return selectedDate;
	}

	public void setSelectedDate(LocalDate selectedDate) {
		this.selectedDate = selectedDate;
	}

	public String getFamilyDoctorDisplayName() {
		return familyDoctorDisplayName;
	}
}
