package com.agilex.healthcare.schedulingmanager.datalayer;


import com.agilex.healthcare.schedulingmanager.datalayer.appointment.AppointmentRequestPo;
import javax.persistence.EntityManager;


@SuppressWarnings("unchecked")
public class ValidPo<T extends PersistenceObject> {
	private boolean ok = true;
	private T po = null;

	public ValidPo(EntityManager entityManager, T obj) {
		if (isNewRecord(obj)) {
			po = null;
			ok = true;
		} else {
			po = (T) entityManager.find(obj.getClass(), obj.getId());
			ok = computeOk(po, obj);
		}
	}

	public boolean isOk() {
		return ok;
	}

	public T getPo() {
		return po;
	}

	private boolean computeOk(AppointmentRequestPo po, AppointmentRequestPo obj) {
		return po.getPatient().getUserId().equalsIgnoreCase(obj.getPatient().getUserId());
	}

	private boolean computeOk(T po, T obj) {
		try {
			if (po instanceof AppointmentRequestPo) {
				return computeOk((AppointmentRequestPo) po, (AppointmentRequestPo) obj);
			}
			return po.getUserId().equalsIgnoreCase(obj.getUserId());
		} catch (NullPointerException e) {
			return true;
		}
	}

	private boolean isNewRecord(T obj) {
		return obj.getId() == null;
	}
}
