/**
 * Moxkiriya standalone Wiki.
 * WikiHistory.
 * 
 * @author Ryuhei Terada
 * See the '<a href="{@docRoot}/copyright.html">Copyright</a>'
 */
package com.wiki.standalone.moxkiriya;

import java.util.ArrayList;

import javax.jcr.Property;

/**
 * Manage wiki history.
 * 
 *
 */
public class WikiHistory {
	/** History list*/
	private ArrayList<PageData> histories_ = new ArrayList<PageData>();

	/** Position on history list. */
	private int position_ = 0;
	
	/**
	 * Constructor.
	 */
	public WikiHistory() {
		histories_.clear();
	}

	/**
	 * Is there an older node on a history list.
	 * @return boolean
	 */
	public boolean canBack() {
		boolean canBack = false;
		
		if(histories_.size() > 1) {
			if(position_ > 0) {
				canBack = true;
			}
		}
		
		return canBack;
	}

	/**
	 * Is there an newer node on a history list.
	 * @return boolean
	 */
	public boolean canForward() {
		boolean canForward = false;
		
		if(histories_.size() > 0) {
			if(position_ < histories_.size() - 1) {
				canForward = true;
			}
		}
		
		return canForward;
	}

	/**
	 * Execute history back.
	 * @return PageData
	 */
	public PageData back() {
		PageData pageData = null;

		if(canBack() == true) {
			position_--;
			pageData = histories_.get(position_);
		}
		
		return pageData;
	}

	/**
	 * Execute history forward.
	 * @return PageData
	 */
	public PageData forward() {
		PageData pageData = null;
		
		if(canForward() == true) {
			position_++;
			pageData = histories_.get(position_);
		}
		
		return pageData;
	}

	/**
	 * Add PageData to history list.
	 * @param pageData
	 * @throws Exception
	 */
	public void add(PageData pageData) throws Exception {
		if(histories_.size() > 0) {
			PageData latestPage = histories_.get(position_);
			String   uuid       = latestPage.getNode().getProperty(Property.JCR_UUID).getString();

			if(pageData.getNode().getProperty(Property.JCR_UUID).getString().equals(uuid) == true) {
				/*
				 * History中に同じページを連続登録しようとした場合、
				 */
				histories_.remove(position_);
			}
			else {
				position_++;				
			}
		}
		
		for(int count = position_; count < histories_.size(); count++) {
			histories_.remove(count);
		}
		
		histories_.add(pageData);
		position_ = histories_.size() - 1;
	}

	/**
	 * Clear history.
	 */
	public void clear() {
		histories_.clear();
		position_ = 0;
	}
}
