package com.agilex.vamf.missionhealth.domain;

import java.io.Serializable;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

import com.agilex.healthcare.utility.NullChecker;
import com.agilex.healthcare.utility.NullSafeStringComparer;

@XmlRootElement(name = "patient-identifier", namespace = Namespace.MissionHealth)
@XmlAccessorType(value = XmlAccessType.NONE)
public class PatientIdentifier implements Serializable {

	private static final long serialVersionUID = 1734590099213237124L;

	@XmlElement
	private String uniqueId;
	@XmlElement
	private String assigningAuthority; // tied to issuer / source

	public PatientIdentifier() {
	}

	public PatientIdentifier(String assigningAuthority, String uniqueId) {
		this.setAssigningAuthority(assigningAuthority);
		this.setUniqueId(uniqueId);
	}

	public PatientIdentifier createCopy() {
		return new PatientIdentifier(this.getAssigningAuthority(), this.getUniqueId());
	}

	@Override
	public boolean equals(Object o) {
		if (o == null) {
			return false;
		}
		if (!(o instanceof PatientIdentifier)) {
			return false;
		}

		PatientIdentifier patientIdentifier = (PatientIdentifier) o;

		// PatientIdentifier
		if (this.assigningAuthority != null && patientIdentifier.getAssigningAuthority() != null){
			return (areStringsEqual(patientIdentifier.getUniqueId(), this.getUniqueId()));
		}else{
			return (areStringsEqual(patientIdentifier.getAssigningAuthority(), this.getAssigningAuthority()) 
					&& areStringsEqual(patientIdentifier.getUniqueId(), this.getUniqueId()));
		}
			
	}

	@Override
	public int hashCode() {
		int hashCode;
		
		if (this.assigningAuthority != null){
			hashCode = (uniqueId == null) ? 0 : uniqueId.hashCode();
		} else {
			String s = toString();
			if (NullChecker.isNullish(s))
				s = "";
			hashCode = s.hashCode();
		}
		
		return hashCode;
	}

	private boolean areStringsEqual(String a, String b) {
		return NullSafeStringComparer.areEqual(a, b);
	}

	public String getUniqueId() {
		return uniqueId;
	}

	public void setUniqueId(String uniqueId) {
		this.uniqueId = uniqueId;
	}

	public String getAssigningAuthority() {
		return assigningAuthority;
	}

	public void setAssigningAuthority(String assigningAuthority) {
		this.assigningAuthority = assigningAuthority;
	}

	@Override
	public String toString() {
		final String delimitor = "#";
		String s;
		if (NullChecker.isNullish(uniqueId)) {
			s = null;
		} else if (NullChecker.isNullish(assigningAuthority)) {
			s = uniqueId;
		} else {
			s = assigningAuthority + delimitor + uniqueId;
		}
		return s;
	}

}
