package gov.va.vinci.dart.biz;

import gov.va.vinci.dart.common.ValidationHelper;
import gov.va.vinci.dart.common.exception.ValidationException;
import gov.va.vinci.dart.service.DartObjectFactory;

import java.util.Date;

import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;

@Entity
//TODO:  PII:  Update Discriminator value after database value is determined
@DiscriminatorValue("4")
public class PreparatoryStudy extends Activity { 

	public static PreparatoryStudy findById(final int activityId) {
		return DartObjectFactory.getInstance().getPreparatoryStudyDAO().findById(activityId);
	}
	
	public static PreparatoryStudy findByShortName(final String name) throws ValidationException {
		ValidationHelper.required("Research Study Short Name", name);
		ValidationHelper.validateSize("Research Study Short Name", name, 1, 1024);
		
		return DartObjectFactory.getInstance().getPreparatoryStudyDAO().findByShortName(name);
	}
	
	protected PreparatoryStudy() {}
	
	public static PreparatoryStudy create(final String activityName, final Date startDate, final Date endDate, final String officialName, final String createdBy) throws ValidationException {
		PreparatoryStudy study = new PreparatoryStudy();
		
		ValidationHelper.required("Created By", createdBy);
		ValidationHelper.validateSize("Created By", createdBy, 1, 32);
		
		study.setCreatedOn(new Date());
		study.setCreatedBy(createdBy);
		
		study.modify(activityName, officialName, createdBy);
		
		DartObjectFactory.getInstance().getPreparatoryStudyDAO().save(study);
		
		return study;
	}
	
	public void modify(final String name, final String officialName, final String updatedBy) throws ValidationException {
		validateModify(name, officialName, updatedBy);
		
		this.name = name;
		this.officialName = officialName;
		this.updatedBy = updatedBy;
		this.updatedOn = new Date();
	}
	
	private void validateModify(final String name, final String officialName, final String updatedBy) throws ValidationException {

		// business rules require that name not be required...
		//ValidationHelper.required("Name", name);
		ValidationHelper.validateSize("Name", name, 0, 1024);
		ValidationHelper.required("Official Name", officialName);
		ValidationHelper.validateSize("Official Name", officialName, 0, 1024);
		ValidationHelper.required("Updated By", updatedBy);
		ValidationHelper.validateSize("Updated By", updatedBy, 0, 32);
		
	}

	@Override
	public int hashCode() {
		return this.id;
	}
	
	// necessary to use (List<PreparatoryStudy>).contains()
	@Override
	public boolean equals(Object obj) {
		if (obj == null) {
			return false;
		}
		
		if ((obj instanceof PreparatoryStudy) == false) {
			return false;
		}
		
		PreparatoryStudy rs2 = (PreparatoryStudy)obj;
		return rs2.getId() == this.getId();
	}
}
