package managedbean.systemAdmin;

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.model.LazyDataModel;
import org.primefaces.model.SortOrder;

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

@Named("listDoctors")
@ViewScoped
public class ListDoctorsByCenterMBean extends ManagedBeanBase implements Serializable {

	private static final long serialVersionUID = 1L;

	private List<PrimaryHealthCareCenterTO> primaryHealthCareCenterList;
	private PrimaryHealthCareCenterTO primaryHealthCareCenter;
	private String lastUIQueryPH;
	private LazyDataModel<FamilyDoctorTO> lazyDataModelDoctorList;

	public ListDoctorsByCenterMBean() {
	}

	@PostConstruct
	public void init() {
		this.primaryHealthCareCenterList = this.getRemoteManagerCommon().listCAPsPaged(0, Constants.MAX_ITEMS_AUTOCOMPLETE_SEARCH);
		this.primaryHealthCareCenter = null;
		this.lastUIQueryPH = "";

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

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

					return getRemoteManagerSystemAdmin().listAllFamilyDoctorsByCAPPaged(primaryHealthCareCenter.getId(), (first / pageSize), pageSize);
				}
			}
		};
	}

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

	public List<PrimaryHealthCareCenterTO> completePrimaryHealCareCenter(String query) {
		if (query != null && query.equals(this.lastUIQueryPH) == false) {
			this.lastUIQueryPH = query;
			this.primaryHealthCareCenterList = this.getRemoteManagerCommon().listCAPsFiltered(query, 0, Constants.MAX_ITEMS_AUTOCOMPLETE_SEARCH);
		}
		return this.primaryHealthCareCenterList;
	}

	public List<PrimaryHealthCareCenterTO> getPrimaryHealthCareCenterList() {
		return primaryHealthCareCenterList;
	}

	public void setPrimaryHealthCareCenterList(List<PrimaryHealthCareCenterTO> value) {
		this.primaryHealthCareCenterList = value;
	}

	public PrimaryHealthCareCenterTO getPrimaryHealthCareCenter() {
		return primaryHealthCareCenter;
	}

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

	public Long getPatientsByDoctor(int familyDoctorId) {
		return getRemoteManagerSystemAdmin().getPatientCount(familyDoctorId);
	}
}
