package com.agilex.vamf.missionhealth.domain.atom;

import java.net.URI;
import java.util.ArrayList;
import java.util.Iterator;

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

import com.agilex.healthcare.utility.NullChecker;

/**
 * 
 * @author j.ray
 */
@XmlRootElement
@XmlAccessorType(value = XmlAccessType.NONE)
public class AtomLinks extends ArrayList<AtomLink> {

	private static final long serialVersionUID = 5347256804902931821L;

	@XmlTransient
	public AtomLink getSelfLink() {
		AtomLink match = null;
		for (AtomLink possibleMatch : this) {
			if (NullChecker.isNotNullish(possibleMatch.getRel()) && rel.self.contentEquals(possibleMatch.getRel())) {
				match = possibleMatch;
				break;
			}
		}
		return match;
	}

	public void setSelfLink(AtomLink link) {
		AtomLink existingLink = getSelfLink();
		if (existingLink != null) {
			this.remove(existingLink);
		}
		if (link != null) {
			link.setRel(rel.self);
			this.add(link);
		}
	}

	@XmlTransient
	public AtomLink getLinkByTitle(String title) {
		AtomLink match = null;
		if (NullChecker.isNotNullish(title)) {
			Iterator<AtomLink> iterator = this.iterator();
			
			while (iterator.hasNext()) {
				AtomLink possibleMatch = iterator.next();
				if (NullChecker.isNotNullish(possibleMatch.getTitle()) && title.contentEquals(possibleMatch.getTitle())) {
					match = possibleMatch;
					break;
				}
			}
		}
		return match;
	}

	@XmlTransient
	public URI getUriByTitle(String title) {
		AtomLink link = getLinkByTitle(title);
		return AtomLink.extractUri(link);
	}

	public void setLinkByTitle(AtomLink link) {
		
		if (link != null && NullChecker.isNotNullish(link.getTitle())) {
			AtomLink existingLink = getLinkByTitle(link.getTitle());
			if (existingLink != null) {
				this.remove(existingLink);
			}
			this.add(link);
		}
	}
	
	public AtomLink addRelatedLink(String title, URI uri) {
		AtomLink link = new AtomLink();
		link.setTitle(title);
		link.setHref(uri);
		link.setRel(rel.related);
		setLinkByTitle(link);
		return link;
	}

	public AtomLink addAlternateLink(String title,URI relatedUri) {
		AtomLink link = new AtomLink();
		link.setTitle(title);
		link.setHref(relatedUri);
		link.setRel(rel.alternate);
		this.add(link);
		return link;
	}

}
