package com.agilex.vamf.missionhealth.domain;

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

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

import org.apache.commons.beanutils.BeanComparator;

import com.agilex.vamf.missionhealth.domain.atom.AtomLink;
import com.agilex.vamf.missionhealth.domain.atom.AtomLinks;
import com.agilex.vamf.missionhealth.domain.atom.rel;


/**
 * 
 * @author j.ray
 */
@XmlAccessorType(value = XmlAccessType.NONE)
@XmlRootElement(namespace = Namespace.MissionHealth)
public class DomainTransferObjectCollection<T> extends ArrayList<T> implements ObjectTypeable  {
	private static final long serialVersionUID = 3341957688902553268L;
	private AtomLinks links = null;

	@XmlElement(name = "link", namespace = Namespace.Atom)
	public AtomLinks getLink() {
		if (this.links == null) {
			this.links = new AtomLinks();
		}

		return this.links;
	}

	public AtomLink getSelfLink() {
		return getLink().getSelfLink();
	}

	public URI getSelfUri() {
		AtomLink link = getSelfLink();
		return AtomLink.extractUri(link);
	}

	public void setSelfUri(URI uri) {
		AtomLink link = new AtomLink();
		link.setHref(uri);
		link.setRel(rel.self);
		getLink().setSelfLink(link);
	}

	@XmlAttribute
	public int getSize() {
		return super.size();
	}
	
	@SuppressWarnings("unchecked")
	private void sort(String property, boolean isDescending){
		
		BeanComparator comparator = new BeanComparator(property);
		Collections.sort(this, comparator);
		if(isDescending){
			Collections.reverse(this);
		}
	}

	public void sortAscending(String property){
		this.sort(property, false);
	}
	
	public void sortDescending(String property){
		this.sort(property, true);
	}

	@XmlElement(name = "object-type")
	public String getObjectType() {
		return this.getClass().getSimpleName();
	}
}
