// WideMargin. Simple fast bible software.
// Copyright (C) 2011  Daniel Hughes
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

using System;
using System.Collections.Generic;

namespace WideMargin.Controller
{
	/// <summary>
	/// Maintains a history of actions performed
	/// And is able to navigate backwards and forward
	/// within that hi
	/// </summary>
	public class History
	{
		private List<Action> _actionHistory;
		private int _position;
		
		/// <summary>
		/// Constructor
		/// </summary>
		public History ()
		{
			_actionHistory = new List<Action>();
			_position = -1;
		}
		
		/// <summary>
		/// Performs and action and adds it
		/// to the histroy.
		/// </summary>
		/// <param name="action">Action to run and record</param>
		public void Perform(Action action)
		{
			//remove everything after the current position
			ClearAfterPosition();
			_actionHistory.Add(action);
			_position++;
			action();
		}
		
		/// <summary>
		/// Clears all actions newer then the current.
		/// This is used when we have gone back into 
		/// history and then perform a new action,
		/// which clears all newer actions.
		/// </summary>
		private void ClearAfterPosition()
		{
			if(_position == _actionHistory.Count - 1)
			{
				return;
			}
			_actionHistory.RemoveRange(_position + 1, _actionHistory.Count - _position - 1);	
		}
		
		/// <summary>
		/// Go back in the history.
		/// </summary>
		public void Back()
		{
			if(_position <= 0)
			{
				return;	
			}
			_position--;

			_actionHistory[_position]();
		}
		
		/// <summary>
		/// Go forward in the history.
		/// </summary>
		public void Forward()
		{
			if(_position >= _actionHistory.Count - 1)
			{
				return;	
			}
			_position++;
			_actionHistory[_position]();
		}
	}
}

