/*
 * @(#)AppletPainter.java	1.0 11-Apr-07
 *
 * IIT Bombay, 
 * Licensed under a Creative Commons Attribution-Noncommercial-Share Alike 2.5 License.
 */
package classes.main;

import java.util.ArrayList;
import java.util.Iterator;

import types.Command;

import interfaces.IShape;
import interfaces.IShapeCommand;
import interfaces.ShapeDecorator;
import classes.shapes.commands.CommandContainer;

/**
 * Paints the graphics commands stored in the command container class
 *
 * @author  Prathab, Mukesh
 * @version 1.0, 25-Mar-07
 * @see classes.shapes.commands.CommandContainer
 * @see interfaces.IShapeDrawer
 */
public class AppletPainter {
	CommandContainer commandContainer;
	IShapeCommand shapeCommand;
	/** 
	 * Initializes with the <tt>IShapeCommand</tt> object and <tt>CommandContainer</tt> object
	 */
	public AppletPainter(IShapeCommand shapeCommand, CommandContainer commandContainer) {
		this.shapeCommand = shapeCommand;
		this.commandContainer = commandContainer;
	}
	
	/** 
	 * Paints the commands stored in the commandConatiner object
	 * and uses the ShapeDrawCommand to draw the shapes
	 * @see classes.shapes.commands.ShapeDrawCommands
	 * @see classes.shapes.commands.CommandContainer
	 */
	public void paint() {
		ArrayList list = commandContainer.getPermanentCommandList();
		if(list != null) {
			Iterator it = list.iterator();
			while(it.hasNext()) {
				Command cmd = (Command) it.next();
				shapeCommand.execute(cmd);
			}
		}
		list = commandContainer.getTemporaryCommandList();
		if(list != null) {
			Iterator it = list.iterator();
			while( it.hasNext()) {
				Command cmd = (Command) it.next();
				shapeCommand.execute(cmd);
			}
			commandContainer.clearTempCommandList();
		}
	}

	/**
	 *  Collects the commands from the <tt>CommandContainer</tt> object
	 */
	public void collectCommands(){
		ArrayList list = commandContainer.getObjectList();
		if(list != null) {
			Iterator it = list.iterator();
			while(it.hasNext()) {
				Object obj = it.next();
				if(obj instanceof IShape) {
					IShape shape = (IShape) obj;
					if(shape.IsPermanentShape()) shape.drawShape();
				}
				else if(obj instanceof ShapeDecorator) {
					ShapeDecorator shapeDecorator = (ShapeDecorator) obj;
					if(shapeDecorator.IsPermanentShape()) shapeDecorator.drawShape();
				}
			}
		}
	}
	
	/**
	 * Collects the commands from the parameter passed
	 * @param list <tt>Arraylist</tt> consists of commands 
	 */
	public void collectCommands(ArrayList list){
		if(list != null) {
			Iterator it = list.iterator();
			while(it.hasNext()) {
				Object obj = it.next();
				if(obj instanceof IShape) {
					IShape shape = (IShape) obj;
					if(shape.IsPermanentShape()) shape.drawShape();
				}
				else if(obj instanceof ShapeDecorator) {
					ShapeDecorator shapeDecorator = (ShapeDecorator) obj;
					if(shapeDecorator.IsPermanentShape()) shapeDecorator.drawShape();
				}
			}
		}
	}
}
