package managedbean.medicalTest;

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

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

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

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

@Named("sspec")
@ViewScoped
public class SearchSpecialistMBean extends ManagedBeanBase implements Serializable {

	private static final long serialVersionUID = 1L;

	private List<MedicalSpecialtyTO> medicalSpecialtiesList;
	private MedicalSpecialtyTO medicalSpecialty;
	private String lastUIQueryMS;
	private LazyDataModel<SpecialistDoctorTO> lazyDataModelDoctorList;

	public SearchSpecialistMBean() {
	}

	@PostConstruct
	public void init() {
		// Inicialización de variables y propiedades van aquí.
		this.medicalSpecialtiesList = this.getRemoteManagerCommon().listMedicalSpecialtiesPaged(0, Constants.MAX_ITEMS_AUTOCOMPLETE_SEARCH);
		this.medicalSpecialty = null;
		this.lastUIQueryMS = "";

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

			@Override
			public List<SpecialistDoctorTO> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, Object> filters) {
				if (medicalSpecialty == null) {
					this.setRowCount(0);
					return null;
				} else {
					Long totalRowCount = getRemoteManagerMedicalTest().getSpecialistDoctorByMedicalSpecialtyCount(medicalSpecialty.getId());
					this.setRowCount(totalRowCount.intValue());

					return getRemoteManagerMedicalTest().findSpecialistDoctorByMedicalSpecialty(medicalSpecialty.getId(), (first / pageSize), pageSize);
				}
			}
		};
	}

	public LazyDataModel<SpecialistDoctorTO> getLazyDataModelDoctorList() {
		return lazyDataModelDoctorList;
	}

	public List<MedicalSpecialtyTO> completeMedicalSpecialty(String query) {
		if (query != null && query.equals(this.lastUIQueryMS) == false) {
			this.lastUIQueryMS = query;
			// Recuperamos las 200 primeras coincidencias
			this.medicalSpecialtiesList = this.getRemoteManagerCommon().listMedicalSpecialtiesFiltered(query, 0, Constants.MAX_ITEMS_AUTOCOMPLETE_SEARCH);
		}
		return this.medicalSpecialtiesList;
	}

	public List<MedicalSpecialtyTO> getMedicalSpecialtiesList() {
		return medicalSpecialtiesList;
	}

	public void setMedicalSpecialtiesList(List<MedicalSpecialtyTO> value) {
		this.medicalSpecialtiesList = value;
	}

	public MedicalSpecialtyTO getMedicalSpecialty() {
		return medicalSpecialty;
	}

	public void setMedicalSpecialty(MedicalSpecialtyTO medicalSpecialty) {
		this.medicalSpecialty = medicalSpecialty;
	}

}
