import java.awt.BasicStroke;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.ButtonGroup;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFileChooser;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButtonMenuItem;

/**
 * 
 */

/**
 * @author Jon Klein, CM2296
 *
 */
public class TopPanel extends JPanel
{
	// Menu design heavily inspired from
	// http://www.java-tips.org/java-se-tips/javax.swing/how-to-create-menu-bar.html

	
	private DrawingPanel dpanel;
	private DrawingArea darea;

	/**
	 * Creates the top menu bar.
	 */
	public TopPanel()
	{
		JMenuBar menuBar = new JMenuBar();
		JMenu fileMenu = new JMenu("File");
		JMenu editMenu = new JMenu("Edit");
		JMenu drawMenu = new JMenu("Draw");
		JMenu textMenu = new JMenu("Text");
		
	    menuBar.add(fileMenu);
	    menuBar.add(editMenu);
	    menuBar.add(drawMenu);
	    menuBar.add(textMenu);
	    
	    JMenuItem newAction = new JMenuItem("New");
	    JMenuItem saveAction = new JMenuItem("Save");
	    JMenuItem loadAction = new JMenuItem("Load");
        JMenuItem exitAction = new JMenuItem("Exit");
        JMenuItem undoAction = new JMenuItem("Undo");
        
        
        // font menu setup
        JRadioButtonMenuItem font1 = new JRadioButtonMenuItem("times new roman");
        JRadioButtonMenuItem font2 = new JRadioButtonMenuItem("helvetica");
        JRadioButtonMenuItem font3 = new JRadioButtonMenuItem("courier");
        font1.setSelected(true);
        JMenuItem fontSize = new JMenuItem("set font size");
        final JCheckBoxMenuItem boldcheck = new JCheckBoxMenuItem("bold");
        
        ButtonGroup fontgroup = new ButtonGroup();
		fontgroup.add(font1);
        fontgroup.add(font2);
        fontgroup.add(font3);
        
        // setup width selection buttons
        JRadioButtonMenuItem width1 = new JRadioButtonMenuItem("line/brush width 1");
        JRadioButtonMenuItem width2 = new JRadioButtonMenuItem("line/brush width 2");
        JRadioButtonMenuItem width3 = new JRadioButtonMenuItem("line/brush width 3");
        JRadioButtonMenuItem width4 = new JRadioButtonMenuItem("line/brush width 4");
        width1.setSelected(true);
        JCheckBoxMenuItem fillshapes = new JCheckBoxMenuItem("fill shapes");
        ButtonGroup widthgroup = new ButtonGroup();
        
        widthgroup.add(width1);
        widthgroup.add(width2);
        widthgroup.add(width3);
        widthgroup.add(width4);

        fileMenu.add(newAction);
        fileMenu.add(saveAction);
        fileMenu.add(loadAction);
        fileMenu.addSeparator();
        fileMenu.add(exitAction);
        editMenu.add(undoAction);
        
//        drawMenu.add(width1); replaced with spinner
//        drawMenu.add(width2);
//        drawMenu.add(width3);
//        drawMenu.add(width4);
//        drawMenu.addSeparator();
        drawMenu.add(fillshapes);
        drawMenu.addSeparator();
        
        textMenu.add(font1);
        textMenu.add(font2);
        textMenu.add(font3);
        textMenu.addSeparator();
        textMenu.add(boldcheck);
        textMenu.addSeparator();
        textMenu.add(fontSize);

        
        
        final JFileChooser filedialog = new JFileChooser();
        filedialog.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        
        this.add(menuBar);

        // menu item action listeners
        newAction.addActionListener(new ActionListener() 
        {
        	public void actionPerformed(ActionEvent arg0) 
        	{
        		dpanel.clearAll();
        	}
        });
        
        saveAction.addActionListener(new ActionListener() 
        {
			public void actionPerformed(ActionEvent arg0) 
            {
				BufferedImage img = new BufferedImage(DrawingArea.FRAME_WIDTH, DrawingArea.FRAME_HEIGHT, BufferedImage.TYPE_INT_ARGB);
				Graphics2D g2img = img.createGraphics();
				if (dpanel.getBackground_image() != null)
				{
					g2img.drawImage(dpanel.getBackground_image(), 0, 0, null);
				}
				for (doodle shape : dpanel.drawn_objects)
				{
					if (shape.text)
					{
						g2img.setFont(new Font(shape.getFace(), shape.getStyle(),  shape.getSize()));
						g2img.setColor(shape.color);
						g2img.drawString(shape.getMessage(), shape.x, shape.y);
						continue;
					}
					g2img.setStroke(new BasicStroke(shape.size));
					if (shape.filled)
					{
						g2img.setColor(shape.fillcolor);
						g2img.fill(shape.shape);
					}

					g2img.setColor(shape.color);
					g2img.draw(shape.shape);
				}
				
				int returnVal = filedialog.showSaveDialog(TopPanel.this);
				
	            if (returnVal == JFileChooser.APPROVE_OPTION) {
	                File file = filedialog.getSelectedFile();
	                File outputfile = new File(file.getAbsolutePath() + ".png");
	                try
					{
						ImageIO.write(img, "png", outputfile);
					} 
					
					catch (IOException e)
					{
						e.printStackTrace();
						System.out.println("Error while saving image. Try mspaint, it is more stable.");
					}
	            }

				
            }
    	});
        
        loadAction.addActionListener(new ActionListener() 
    	{
            public void actionPerformed(ActionEvent arg0) 
            {
            	int returnVal = filedialog.showOpenDialog(TopPanel.this);

                if (returnVal == JFileChooser.APPROVE_OPTION) {
                     File file = filedialog.getSelectedFile();
                    try
					{
						BufferedImage input = ImageIO.read(file);
						dpanel.setBackgroundImage(input);
					} 
                    
                    catch (IOException e)
					{
						System.out.println("Error: you failed to select an image..");
						e.printStackTrace();
					}
                    
                } 
                
            }
    	});
        
        
        exitAction.addActionListener(new ActionListener() 
    	{
            public void actionPerformed(ActionEvent arg0) 
            {
            	darea.exit();
            }
    	});
        
        undoAction.addActionListener(new ActionListener() 
    	{
            public void actionPerformed(ActionEvent arg0) 
            {
                dpanel.undo();
            }
    	});
        
        width1.addActionListener(new ActionListener() 
    	{
            public void actionPerformed(ActionEvent arg0) 
            {
                dpanel.setBrushWidth(1);
            }
    	});
        
        width2.addActionListener(new ActionListener() 
    	{
            public void actionPerformed(ActionEvent arg0) 
            {
                dpanel.setBrushWidth(2);
            }
    	});
        
        width3.addActionListener(new ActionListener() 
    	{
            public void actionPerformed(ActionEvent arg0) 
            {
                dpanel.setBrushWidth(3);
            }
    	});
        
        width4.addActionListener(new ActionListener() 
    	{
            public void actionPerformed(ActionEvent arg0) 
            {
                dpanel.setBrushWidth(4);
            }
    	});
        
        fillshapes.addActionListener(new ActionListener() 
    	{
            public void actionPerformed(ActionEvent arg0) 
            {
                dpanel.fillshapes = ! dpanel.fillshapes;
            }
    	});
        
        font1.addActionListener(new ActionListener() 
    	{
            public void actionPerformed(ActionEvent arg0) 
            {
                dpanel.setFontFace("TimesRoman");
            }
    	});
        
        font2.addActionListener(new ActionListener() 
    	{
            public void actionPerformed(ActionEvent arg0) 
            {
                dpanel.setFontFace("Helvetica");
            }
    	});
        
        font3.addActionListener(new ActionListener() 
    	{
            public void actionPerformed(ActionEvent arg0) 
            {
                dpanel.setFontFace("Courier");
            }
    	});
        
        
        boldcheck.addActionListener(new ActionListener() 
    	{
            public void actionPerformed(ActionEvent arg0) 
            {
            	
                dpanel.setFontStyle(boldcheck.isSelected() ? Font.BOLD : Font.PLAIN);
            }
    	});
        
        fontSize.addActionListener(new ActionListener() 
        {
        	public void actionPerformed(ActionEvent arg0) 
        	{
        		try
        		{
            		dpanel.setFontSize(Integer.parseInt(JOptionPane.showInputDialog("enter a font size")));
        		}
        		catch (NumberFormatException e){}
        		
        		
        	}
        });
        
}

	/**
	 * @param dpanel A DrawingPanel, so the top panel can communicate with it.
	 */
	public void addDrawPanel(DrawingPanel dpanel)
	{
		this.dpanel = dpanel;
		
	}

	/**
	 * @param darea A drawing area, so the top panel can close it if called upon to do so.
	 */
	public void addDrawArea(DrawingArea darea)
	{
		this.darea = darea;
		
	}

}
