// Yura Mamyrin

package risk.ui.SwingGUI;

import risk.engine.*;
import risk.engine.core.*;

import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.border.*;
import javax.swing.colorchooser.*;
import javax.swing.filechooser.*;
import java.awt.image.BufferedImage;

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
import java.net.*;
import javax.imageio.ImageIO;

/**
 * @author Yura Mamyrin
 */

public class MapEditor extends JPanel implements ActionListener, SwingGUITab {

	private Risk myrisk;
	private RiskGame myMap;
	private MapEditorPanel editPanel;
	private JToolBar toolbar;

	private JRadioButton move;
	private JRadioButton moveall;
	private JRadioButton join;
	private JRadioButton join1way;
	private JRadioButton disjoin;
	private JRadioButton draw;

	public MapEditor(Risk r) {

		setName( "Map Editor" );

		setOpaque(false);

		myrisk = r;

		toolbar = new JToolBar();

		toolbar.setRollover(true);
		toolbar.setFloatable(false);

		JButton newmap = new JButton("New map");
		newmap.setActionCommand("newmap");
		newmap.addActionListener(this);
		toolbar.add(newmap);

		JButton load = new JButton("Load map");
		load.setActionCommand("load");
		load.addActionListener(this);
		toolbar.add(load);


		JButton save = new JButton("Save map");
		save.setActionCommand("save");
		save.addActionListener(this);
		toolbar.add(save);


		JButton play = new JButton("Play Map");
		play.setActionCommand("play");
		play.addActionListener(this);
		toolbar.add(play);


		toolbar.addSeparator();


		JButton loadimagepic = new JButton("Load Image Pic");
		loadimagepic.setActionCommand("loadimagepic");
		loadimagepic.addActionListener(this);
		toolbar.add(loadimagepic);

		JButton loadimagemap = new JButton("Load Image Map");
		loadimagemap.setActionCommand("loadimagemap");
		loadimagemap.addActionListener(this);
		toolbar.add(loadimagemap);


		editPanel = new MapEditorPanel();

		editPanel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0,0,0),1));

		JScrollPane scroll = new JScrollPane(editPanel);

		Dimension size = new Dimension(PicturePanel.PP_X , PicturePanel.PP_Y);

		scroll.setPreferredSize(size);
		scroll.setMinimumSize(size);
		scroll.setMaximumSize(size);

		scroll.setBorder(null);

		setLayout( new BorderLayout() );

		JPanel tmp = new JPanel();
		tmp.setOpaque(false);
		tmp.add(scroll);
		add( tmp );

		ButtonGroup modes = new ButtonGroup();
		JPanel modesPanel = new JPanel();
		modesPanel.setOpaque(false);

		move = new JRadioButton("move");
		moveall = new JRadioButton("move all");

		join = new JRadioButton("join");
		join1way = new JRadioButton("join 1 way");
		disjoin = new JRadioButton("disjoin");

		draw = new JRadioButton("draw");

		modes.add(move);
		modes.add(moveall);
		modes.add(join);
		modes.add(join1way);
		modes.add(disjoin);
		modes.add(draw);

		modesPanel.add(move);
		modesPanel.add(moveall);
		modesPanel.add(join);
		modesPanel.add(join1way);
		modesPanel.add(disjoin);
		modesPanel.add(draw);

		add(modesPanel, BorderLayout.SOUTH );

		JPanel topPanel = new JPanel();
		topPanel.setOpaque(false);

		topPanel.add(new JSlider());

		add(topPanel, BorderLayout.NORTH );
	}


	public JToolBar getToolBar() {

		return toolbar;

	}
	public JMenu getMenu() {

		return null;

	}



/*

things to add:



menu at the top:
new map, will prompt to select image
(or maybe just make a white box[choose size], and then when countries are made, it will auto fill them with the continent color)
---
load --> maybe load from ANY location, not just map location?
save --> should save all image files, and cards file, maybe just prompt for name, then check overrides and save it in default location
---
load new image, will auto change the size, will warn if its the wrong size, or resize it and then resave it
load new map(gif file)
---
fade main image in and out/ or hide it
display the gif file ontop, ######## with edit options, display list of countries, and brush sizes ########


views:
view countries, for edit and to select for painting
view continents -> add remove
view cards -> add remove
view missions -> add remove
EDIT!!!

mouse modes:
(nothing)
add country
remove country
make join
make 1 way join
unjoin
(drag whole map around)
draw - edit gif file

*/

	private MapEditorViews views;
	public void setVisible(boolean v) {

		super.setVisible(v);

		if (v && views == null ) {

			views = new MapEditorViews( Risk.findParentFrame(this) );

		}

		if (views!= null) {

			if (v) {

				Frame frame = Risk.findParentFrame(this);

				Dimension frameSize = frame.getSize();
				Point frameLocation = frame.getLocation();

				views.setLocation(frameLocation.x+frameSize.width, frameLocation.y);
				views.setSize(200, frameSize.height);

				JOptionPane.showMessageDialog(this,"THE MAP EDITOR DOES NOT WORK YET\nIT CAN ONLY VIEW MAPS WITH BASIC EDITING, NO SAVING\nTHIS IS ONLY HERE IF ANYONE WANTS TO PLAY AROUND WITH IT");

			}

			views.setVisible(v);

		}


	}

	public void setNewMap(RiskGame m,BufferedImage ip,BufferedImage im) {

		myMap = m;

		editPanel.setMap(myMap);
		views.setMap(myMap);

		editPanel.setImagePic(ip);
		editPanel.setImageMap(im);

		revalidate();
		repaint();

	}

	public RiskGame makeNewMap() throws Exception {

		RiskGame rg = new RiskGame();



		for (int c=1;c<=RiskGame.MAX_PLAYERS;c++) {

			rg.addPlayer(
				Player.PLAYER_HUMAN,
				"PLAYER"+c,
				risk.engine.core.RiskGame.getColor( myrisk.getRiskConfig("default.player"+c+".color") ),
				null
			);



		}

		return rg;
	}

	public void actionPerformed(ActionEvent a) {

		if (a.getActionCommand().equals("newmap")) {

			try {

				RiskGame map = makeNewMap();
				map.setupNewMap();

				BufferedImage ipic = new BufferedImage(PicturePanel.PP_X , PicturePanel.PP_Y, BufferedImage.TYPE_INT_BGR);
				BufferedImage imap = new BufferedImage(PicturePanel.PP_X , PicturePanel.PP_Y, BufferedImage.TYPE_INT_BGR);

				setNewMap(map,ipic,imap);

			}
			catch(Exception ex) {

				ex.printStackTrace();

			}

		}
		else if (a.getActionCommand().equals("load")) {


			try {
				String name = Risk.getNewFile( Risk.findParentFrame(this), "map" );

				RiskGame map = makeNewMap();
				map.setMapfile(name); // this is here just to update the cards option
				map.loadMap(name);
				map.loadCards( map.getCardsFile() );

				BufferedImage ipic = ImageIO.read( new URL(Risk.mapsdir,map.getImagePic()) );
				BufferedImage imap = ImageIO.read( new URL(Risk.mapsdir,map.getImageMap()) );

				map.setMemoryLoad();



				setNewMap(map,ipic,imap);


			}
			catch(Exception ex) {

				ex.printStackTrace();

			}

		}
		else if (a.getActionCommand().equals("save")) {

			//@todo: save does not work fully
			// also the map panel keeps the countries in vectors, where as really they r inside the map object
			// this needs to be merged into 1
			return;
/*
		    try {

			JFileChooser fc = new JFileChooser( new File(new URI(Risk.mapsdir.toString())) );
			RiskFileFilter filter = new RiskFileFilter(RiskFileFilter.RISK_MAP_FILES);
			fc.setFileFilter(filter);

			int returnVal = fc.showSaveDialog( Risk.findParentFrame(this) );

			if (returnVal == JFileChooser.APPROVE_OPTION) {

				File file = fc.getSelectedFile();


				String fileName = file.getAbsolutePath();

				if (!(fileName.endsWith( "." + RiskFileFilter.RISK_MAP_FILES ))) {
					fileName = fileName + "." + RiskFileFilter.RISK_MAP_FILES;
				}


				editPanel.saveMap( new File( fileName ) );

			}

		    }
		    catch(Exception ex) {

			ex.printStackTrace();

		    }
*/
		}
		else if (a.getActionCommand().equals("play")) {

			myrisk.newMemoryGame(myMap,editPanel.getImagePic() );

		}
		else if (a.getActionCommand().equals("loadimagepic")) {

		    try {


			JFileChooser fc = new JFileChooser( new File(new URI(Risk.mapsdir.toString())) );

			int returnVal = fc.showOpenDialog( Risk.findParentFrame(this) );

			if (returnVal == JFileChooser.APPROVE_OPTION) {

				editPanel.setImagePic( ImageIO.read( fc.getSelectedFile() ) );

				revalidate();
				repaint();


			}

		    }
		    catch(Exception ex) {

			ex.printStackTrace();

		    }

		}
		else if (a.getActionCommand().equals("loadimagemap")) {

		    try {

			JFileChooser fc = new JFileChooser( new File(new URI(Risk.mapsdir.toString())) );

			int returnVal = fc.showOpenDialog( Risk.findParentFrame(this) );

			if (returnVal == JFileChooser.APPROVE_OPTION) {

				editPanel.setImageMap( ImageIO.read( fc.getSelectedFile() ) );

				repaint();

			}

		    }
		    catch(Exception ex) {

			ex.printStackTrace();

		    }

		}
		else {

			throw new RuntimeException("unknown command: "+a.getActionCommand());

		}


	}

	public BufferedImage getImageMap() {

		return editPanel.getImageMap();

	}


	public BufferedImage getImagePic() {

		return editPanel.getImagePic();

	}



}
