package sim;

import java.awt.event.*;
import java.awt.*;
import java.io.FileFilter;
import java.io.IOException;
//import java.nio.file.*;

public class AddListener extends MouseAdapter implements MouseMotionListener {

	private Wrapper prototype;
	private CreationModule structure;

	public AddListener() {
		this.prototype = null;
		this.structure = null;
	}

	public void setStructure(CreationModule cm) {
		this.structure = cm;
		this.prototype = cm.createWrapper();
		if (cm instanceof sim.lib.others.Module) {
			//GET INPUT MODULE FILE NAME //NEED TO MOVE THIS TO ONLY DO IT WHEN MODULE FIRST SELECTED
			SaveLoadShortcut.FILEDIALOG.setDirectory(SaveLoadShortcut.LASTPATH);
			SaveLoadShortcut.FILEDIALOG.setTitle("Open");
			SaveLoadShortcut.FILEDIALOG.setMode(FileDialog.LOAD);
			SaveLoadShortcut.FILEDIALOG.setFile("*.toy");
			SaveLoadShortcut.FILEDIALOG.setVisible(true);
			String inFile = SaveLoadShortcut.FILEDIALOG.getFile();
			inFile = SaveLoadShortcut.FILEDIALOG.getDirectory() + inFile;
//			Path modfile = Paths.get(SaveLoadShortcut.FILEDIALOG.getFiles()[0].getAbsolutePath());
//			Path base = Paths.get(System.getProperty("user.dir"));
//			Path pathRelative = base.relativize(modfile);
//			inFile = pathRelative.toString();
			((sim.lib.others.Module) prototype).setPath(inFile);
		}
		this.prototype.changeColor(Color.green);
	}

	public void mouseClicked(MouseEvent e) {
	}

	public void mouseEntered(MouseEvent e) {
		Point gridPosition = CentralPanel.ACTIVE_GRID.convertToGrid(e.getX(), e.getY());

		this.prototype.setGridLocation(gridPosition);
		CentralPanel.ACTIVE_GRID.addModule(this.prototype);
	}

	public void mouseExited(MouseEvent e) {
		CentralPanel.ACTIVE_GRID.removeModule(this.prototype);
	}

	public void mousePressed(MouseEvent e) {
	}

	public void mouseReleased(MouseEvent e) {
		// mouse button 2
		if ((e.getModifiers() & Event.META_MASK) != 0) {
			WestPanel.MODE_CONTROL.switchToEditMode();
		} // mouse button 3
		else if ((e.getModifiers() & Event.ALT_MASK) != 0) {
		} // mouse button 1
		else {
			if (this.prototype.canDrop()) {
				Wrapper toAdd = this.structure.createWrapper(this.prototype.getGridLocation());
				CentralPanel.ACTIVE_GRID.addModule(toAdd);
				toAdd.droped();
				SouthPanel.STATUS_BOX.resetComment();
			} else {
				SouthPanel.STATUS_BOX.setComment("can not drop here");
			}
		}
	}

	public void mouseDragged(MouseEvent e) {
		Point gridPosition = CentralPanel.ACTIVE_GRID.convertToGrid(e.getX(), e.getY());
		CentralPanel.ACTIVE_GRID.moveToFree(this.prototype, gridPosition);
	}

	public void mouseMoved(MouseEvent e) {
		Point gridPosition = CentralPanel.ACTIVE_GRID.convertToGrid(e.getX(), e.getY());
		CentralPanel.ACTIVE_GRID.moveToFree(this.prototype, gridPosition);
	}

	public Wrapper getPrototype() {
		return this.prototype;
	}

	public CreationModule getStructure() {
		return this.structure;
	}

	public void resetStructure() {
		this.structure = null;
		this.prototype = null;
	}
}
