package nl.nikhef.safaripark.editpane;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.swing.Action;

import nl.nikhef.sfp.ddmi.DDMIContext;
import nl.nikhef.sfp.ddmi.DataSource;


/**
 * Links the editor to the I2CLink. 
 * 
 * @author Vincent van Beveren (v.van.beveren [at] nikhef.nl)
 */
public class EditorContext 
{

	
	private List<ValueEditor>	_editor	= new ArrayList<ValueEditor>();
	private Set<ValueEditor>	_dirty	= new HashSet<ValueEditor>();
	private DDMIContext			_ctx	= null;
	private boolean				_batchProc = false;
	private Action 				_apply;
	private Action 				_revert;
	private Action 				_reload;
	
	public EditorContext(Action apply, Action revert, Action reload) {
		_apply = apply;
		_revert = revert;
		_reload = reload;
	}

	void addEditor(ValueEditor editor)
	{
		_editor.add(editor);
	}
	

	/**
	 * Set the link, or NULL if there is no link.
	 * 
	 * @param ctx		The Link.
	 */
	public void setContext(DDMIContext ctx)
	{
		_ctx = ctx;
		
		_dirty.clear();
		
		for (ValueEditor ve : _editor)
		{
			ve.updateEditor();
		}
	}

	
	/**
	 * Returns whether or not some components are dirty.
	 * 
	 * @return
	 */
	public boolean someAreDirty() 
	{
		return _dirty.size() != 0;
	}

	
	void updateButtons()
	{
		if (someAreDirty()) {
			_apply.setEnabled(true);
			_revert.setEnabled(true);
			_reload.setEnabled(false);
		} else {
			_apply.setEnabled(false);
			_revert.setEnabled(false);
			if (_ctx != null) {
				_reload.setEnabled(true);
			} else {
				_reload.setEnabled(false);
			}
		}
	}
	
	/**
	 *  
	 */
	public void commit() 
	{
		_batchProc = true;
		for (ValueEditor ve : _dirty)
		{
			ve.commit();
		}
		_dirty.clear();
		_batchProc = false;
		updateButtons();
	}

	public void revert() 
	{
		_batchProc = true;
		for (ValueEditor ve : _dirty)
		{
			ve.revert();
		}
		_dirty.clear();
		_batchProc = false;
		updateButtons();
	}

	public void reload() {
		
		if (_ctx == null) return;
		for (DataSource ds : _ctx.getDDMI().getSources()) {
			ds.clearCache(_ctx);
		}
		
		for (ValueEditor ve : _editor)
		{
			ve.updateEditor();
		}
	}
	
	
	public DDMIContext getContext()
	{
		return _ctx;
	}


	
	
	public void changeDirtyState(ValueEditor valueEditor) {
		if (_batchProc) return;
		if (valueEditor.dirty) 
		{
			if (!_dirty.contains(valueEditor)) _dirty.add(valueEditor);
		}
		else
		{
			if (_dirty.contains(valueEditor)) _dirty.remove(valueEditor);
		}
		updateButtons();
	}

	
}
