package cz.vutbr.feec.gui;

import java.util.Vector;

import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
import cz.vutbr.feec.project.GlobalParameters;
import cz.vutbr.feec.transportObjects.OtherObjectCrate;
import cz.vutbr.feec.transportObjects.ReckCrate;

public class OtherCanvas {

	private Canvas canvas;
	private Vector<OtherObjectInCanvas> objects = new Vector<OtherObjectInCanvas>();
	private int width = 100;
	private int height = 100;
	private int imageSize = 25;

	public int getImageSize() {
		return imageSize;
	}

	private OtherObjectInCanvas selectedObject;

	public OtherObjectInCanvas getSelectedObject() {
		return selectedObject;
	}

	public void setSelectedObject(OtherObjectInCanvas selectedObject) {
		this.selectedObject = selectedObject;
	}

	public OtherCanvas(Canvas canvas) {
		this.canvas = canvas;
		createInitialObjects();
		paintCanvas();
	}

	public Canvas getCanvas() {
		return canvas;
	}

	public void addObject(OtherObjectInCanvas object) {
		objects.add(object);
	}

	public void removeReck(ReckInCanvas reck) {
	}

	public Vector<OtherObjectInCanvas> getObjects() {
		return objects;
	}

	public void paintCanvas() {
		canvas.setWidth(width);
		canvas.setHeight(height);
		GraphicsContext gc = canvas.getGraphicsContext2D();
		gc.setFill(Color.WHITESMOKE);
		gc.fillRect(0, 0, width, height);
		for (int i = 0; i < objects.size(); i++) {
			OtherObjectCrate object = new OtherObjectCrate(objects.get(i));
			paintObject(object, gc);
		}

	}

	private void createInitialObjects() {
		OtherObjectInCanvas object1 = new OtherObjectInCanvas(10, 10, 1, 1,
				GlobalParameters.rampImage, true, this);
		addObject(object1);
		OtherObjectInCanvas object2 = new OtherObjectInCanvas(45, 10, 1, 1,
				GlobalParameters.borderImage, false, this);
		addObject(object2);
	}

	private void paintObject(OtherObjectCrate object, GraphicsContext gc) {
		int x = object.sizeX * imageSize;
		int y = object.sizeY * imageSize;
		int xCycle = x / imageSize;
		int yCycle = y / imageSize;
		int posX = object.posX;
		int posY = object.posY;

		for (int i = 0; i < xCycle; i++) {
			posY = object.posY;
			if (i > 0) {
				posX = posX + imageSize;
			}
			for (int j = 0; j < yCycle; j++) {

				if (j > 0) {
					posY = posY + imageSize;
				}

				gc.drawImage(object.image, posX, posY, imageSize, imageSize);
				// pokial je niektory reck vybrany vykreslim okolo neho cervene
				// ciary
				if (object.object == this.selectedObject) {
					gc.setLineWidth(1);
					gc.setStroke(Color.RED);
					gc.strokeRect(posX - 1, posY - 1, imageSize + 2,
							imageSize + 2);
				}

			}
		}
	}

}