package org.openmhp.system;

import java.awt.*;
// import javax.swing.*;
import java.awt.event.*;
import org.openmhp.util.*;
import org.dvb.event.*;

/* miknov: stripped of all extra functionality and changed from swing to awt. */ 

/**
* Main window
*/
public class TVScreen extends Frame /* implements ActionListener, MouseMotionListener, MouseListener, FocusListener, WindowListener, KeyListener */ {

    public boolean isVisible() { return true; } // miknov
    public boolean isShowing() { return true; } // miknov

    private MHPDevice mhpdevice;
    private Image image;
    private Graphics buffer;

    // public static TVScreen instance;

    // private JPopupMenu popupmenu;

	private String title = "TVScreen for OpenMHP";
	
	private Robot robot;
	private boolean coordinatesOn = false;
	private boolean decColorsOn = false;
	private boolean hexColorsOn = false;
	
    // private InfoFrame infoFrame;
    // private JCheckBoxMenuItem info;
	private boolean dragging = false;
	private int dragStartX = -1;
	private int dragStartY = -1;
    // private ClipArea clipArea;
    // private ColorChecker colorChecker;
	
    protected TVScreen () {// miknov: Output output) {
		super();
		setTitle(title);
		// output.setOwner(this);
		mhpdevice = MHPDevice.getInstance();
		setSize(720+6,576+25);
		// setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE );
	
		// clipArea = new ClipArea();
		// getContentPane().add(clipArea);

		// colorChecker = new ColorChecker(this);
		// getContentPane().add(colorChecker);

		// getContentPane().add(mhpdevice);
		add(mhpdevice);
		setResizable(false);
		//add(mhpdevice);

		// infoFrame = new InfoFrame(getX()+getWidth(),getY());
		// infoFrame.addWindowListener(infoFrame);
		
		
		// popupmenu = new JPopupMenu();

		/*
		JRadioButtonMenuItem nopalette = new JRadioButtonMenuItem("Millions of colors");
		nopalette.addActionListener(this);
		nopalette.setActionCommand("nopalette");
		popupmenu.add(nopalette);
		nopalette.setSelected(true);
		
		JRadioButtonMenuItem palette = new JRadioButtonMenuItem("MHP palette");
		palette.addActionListener(this);
		palette.setActionCommand("palette");
		popupmenu.add(palette);

		JMenuItem check = new JMenuItem("Check non-MHP colors");
		check.addActionListener(this);
		check.setActionCommand("check");
		popupmenu.add(check);
		
		// tejopa 24.8.2004
		info = new JCheckBoxMenuItem("Show info window");
		info.addActionListener(this);
		info.setActionCommand("info");
		popupmenu.add(info);
		*/

		/*
		ButtonGroup group = new ButtonGroup();
    	group.add(nopalette);
   		group.add(palette);
		*/

		// tejopa 24.8.2004
		try { 
			robot = new Robot();
		}
		catch (Exception e) { }



		/* miknov: The following, along with overwritten
		 * isVisible and isShowing operations allowes xlets to
		 * be run without java's gui windows,
		 * ie. "invisibly". This method -- however -- requires
		 * X to be run, and is only a trick to fool java. */
		/*
		setFocusableWindowState(false);
		// setEnabled(false);
		setVisible(true);
		setVisible(false);
		// setEnabled(true);
		setFocusableWindowState(true);
		*/

		/* miknov: flip window on and off (to make AWT create
		 * widget peers, apparently) */
		setVisible(true);
		setVisible(false);
		
		/*
		addFocusListener(this);
		addKeyListener(this);
		addMouseListener(this);
		addMouseMotionListener(this);
		addWindowListener(this);
		*/

		// instance = this; // miknov
	}
/*
	public static TVScreen createTVScreen() {
		if (instance == null) instance = new TVScreen();	
		return instance;
	}

	public static TVScreen getInstance() {	return instance; }
*/

/*
	public void paint(Graphics g) {
		super.paint(g);

		//BufferedImage preImage = new BufferedImage(720, 576, BufferedImage.TYPE_INT_RGB);
		//Graphics2D g2d = preImage.createGraphics();
		if (image == null) image = createImage(720,576);
		buffer = image.getGraphics();

		mhpdevice.paint(buffer);

		g.drawImage(image.getScaledInstance(getWidth(),getHeight(),Image.SCALE_FAST),0,0,getWidth(),getHeight(),null);

		System.out.println(getWidth()+"x"+getHeight());
	}
*/

	public MHPDevice getMHPDevice() { return mhpdevice;	}

	public static void main(String[] args) { }

	public void focusGained(FocusEvent e) {	getMHPDevice().repaint(); }

	public void focusLost(FocusEvent e) { getMHPDevice().repaint(); }

    /*
	public  void windowOpened(WindowEvent e) { System.out.println(e); }
	public  void windowClosing(WindowEvent e) { System.out.println(e); }
	public  void windowClosed(WindowEvent e) { System.out.println(e.getSource()); }
	public  void windowIconified(WindowEvent e) { System.out.println(e);; }
	public  void windowDeiconified(WindowEvent e) { System.out.println(e); }
	public  void windowActivated(WindowEvent e) { 		getMHPDevice().repaint(); }
	public  void windowDeactivated(WindowEvent e) { System.out.println(e); }

	public void mouseEntered(MouseEvent e) { }
	public void mouseExited(MouseEvent e) { }
	public void mousePressed(MouseEvent e) { 
		dragStartX = e.getX();
		dragStartY = e.getY();
	}
	public void mouseReleased(MouseEvent e) { 
		dragging = false;
		clipArea.setArea(0,0,0,0);
		repaint();
	}

	public void mouseClicked(MouseEvent e) { 
		int x = e.getX();
		int y = e.getY();
		int clicks = e.getClickCount();

		if (e.getButton()==MouseEvent.BUTTON3) {
			
			popupmenu.show(this, e.getX(), e.getY());
          
		}
	}

	// MOUSEMOTION LISTENER 24.8.2004 tejopa
	public void mouseDragged(MouseEvent e) {
		dragging = true;
		repaint();
		createInfo(e);
	}
	public void mouseMoved(MouseEvent e) {
		createInfo(e);	
	}

	private void createInfo(MouseEvent e) {
		int x = e.getX();
		int y = e.getY();
		String coords = " ("+(x-2)+","+(y-21)+")";
		Color c = robot.getPixelColor(x+getX(),y+getY());
		int r = c.getRed();
		int g = c.getGreen();
		int b = +c.getBlue();
		String hr = Integer.toHexString(c.getRed());
		String hg = Integer.toHexString(c.getGreen());
		String hb = Integer.toHexString(c.getBlue());
		
		if (hr.length()==1) hr = "0"+hr;
		if (hg.length()==1) hg = "0"+hg;
		if (hb.length()==1) hb = "0"+hb;
		
		String dcolor = " ("+r+","+g+","+b+")"; 
		String hcolor = " #"+hr.toUpperCase()+hg.toUpperCase()+hb.toUpperCase(); 
		String result = title;
		if (coordinatesOn) result+=coords;
		if (decColorsOn) result+=dcolor;
		if (hexColorsOn) result+=hcolor;
		infoFrame.setCoordinateString(coords);
		infoFrame.setDecColorString(dcolor);
		infoFrame.setHexColorString(hcolor);		
		if (dragging) {
			infoFrame.setRegionString(""+(x-dragStartX)+"x"+(y-dragStartY));	
			int xs = 0;
			int ys = 0;
			int w = 0;
			int h = 0;
			if (dragStartX<=x) { xs = dragStartX; w = x-xs; }
			if (dragStartX>x) { xs = x; w = dragStartX-x; }
			if (dragStartY<=y) { ys = dragStartY; h = y-ys; }
			if (dragStartY>y) { ys = y; h = dragStartY-y; }
			
			clipArea.setArea(xs,ys,w,h);
		} else{
			infoFrame.setRegionString("0x0");
		}
	
	}


	public void keyReleased(KeyEvent e) {
		System.out.println(e.toString());		
	}
	public void keyTyped(KeyEvent e) {
		System.out.println(e.toString());		
	}

	public void keyPressed(KeyEvent e) {
		System.out.println(e.toString());
			EventManager.getInstance().fireUserEvent(this,new KeyEvent(this, KeyEvent.KEY_PRESSED, System.currentTimeMillis(), 0, e.getKeyCode()));
  	}
    */
    //	public void actionPerformed(ActionEvent e) {
    //		String cmd = e.getActionCommand();
		/*
		if (cmd=="nopalette") { org.dvb.ui.DVBGraphicsImpl.setMode(org.dvb.ui.DVBGraphicsImpl.NO_PALETTE); }
		if (cmd=="palette") { org.dvb.ui.DVBGraphicsImpl.setMode(org.dvb.ui.DVBGraphicsImpl.PALETTE); }

		if (cmd=="info") {
			if (info.isSelected()) { infoFrame.setVisible(true); }
			else { infoFrame.setVisible(false); }
		}

		if (cmd=="check") {
			colorChecker.paintCheck(getGraphics());
		}
		*/
		
		
				
    //	}

    /*
	class InfoFrame extends JFrame implements WindowListener {
		
		JTextField coordinates;
		JTextField decColor;
		JTextField hexColor;
		JTextField region;
				
		public InfoFrame(int x, int y) {
			super("Info");
			setLocation(x,y);
			setVisible(false);
			setSize(250,108);
			setResizable(false);
			int c = 4;
			Box layout = new Box(BoxLayout.Y_AXIS);
        	Box[] lines = new Box[c];
        	JLabel[] labels = new JLabel[c];
        	
	        labels[0] = new JLabel(" Coordinates (X,Y):",JLabel.RIGHT);
    	    labels[1] = new JLabel(" Color (RGB):",JLabel.RIGHT);
    	    labels[2] = new JLabel(" Color (hex):",JLabel.RIGHT);
    	    labels[3] = new JLabel(" Region (WxH):",JLabel.RIGHT);

        	labels[0].setPreferredSize(new Dimension(120, 27));
        	labels[1].setPreferredSize(new Dimension(120, 27));
        	labels[2].setPreferredSize(new Dimension(120, 27));
        	labels[3].setPreferredSize(new Dimension(120, 27));
                	
        	lines[0] = new Box(BoxLayout.X_AXIS);
        	coordinates = new JTextField("(0,0)");
        	lines[0].add(labels[0]);
        	lines[0].add(coordinates);

        	lines[1] = new Box(BoxLayout.X_AXIS);
        	decColor = new JTextField("(0,0,0)");
        	lines[1].add(labels[1]);
        	lines[1].add(decColor);

        	lines[2] = new Box(BoxLayout.X_AXIS);
        	hexColor = new JTextField("#FFFFFF");
			lines[2].add(labels[2]);
        	lines[2].add(hexColor);

        	lines[3] = new Box(BoxLayout.X_AXIS);
        	region = new JTextField("(0,0)");
			lines[3].add(labels[3]);
        	lines[3].add(region);


        	layout.add(lines[0]);
        	layout.add(lines[1]);
        	layout.add(lines[2]);
        	layout.add(lines[3]);        	
        	this.getContentPane().add(layout);
		}

		public void setCoordinateString(String s) {
			coordinates.setText(s);
		}

		public void setDecColorString(String s) {
			decColor.setText(s);
		}

		public void setHexColorString(String s) {
			hexColor.setText(s);
		}

		public void setRegionString(String s) {
			region.setText(s);
		}

		public void windowOpened(WindowEvent e) { info.setSelected(true); }
		public void windowClosing(WindowEvent e) { info.setSelected(false); }
		public void windowClosed(WindowEvent e) { info.setSelected(false); }
		public void windowIconified(WindowEvent e) { }
		public void windowDeiconified(WindowEvent e) {  }
		public void windowActivated(WindowEvent e) {  }
		public void windowDeactivated(WindowEvent e) { }

	}
    */

    /*
	class ClipArea extends Component {
		public ClipArea() { setSize(720,576); setLocation(0,0); validate(); setVisible(true); }
		private int startX = 0;
		private int startY = 0;
		private int width = 0;
		private int height = 0;
		public void paint(Graphics g) {
			g.setColor(Color.black);
			g.drawRect(startX,startY,width,height);	
		}
		public void setArea(int x, int y, int w, int h) {
			startX = x-3; startY = y-22; width = w; height = h;
			this.repaint();
		}
	}
    */

    /*
	class ColorChecker extends Component {
		MHPPaletteUtil paletteUtil;
		Component parent;
		public ColorChecker(Component p) { 
			parent = p;
			setSize(720,576); setLocation(0,0); 
			setVisible(true);
			paletteUtil = MHPPaletteUtil.getInstance();
		}

		private void paintCheck(Graphics g) {
			for (int x=0;x<parent.getWidth();x++) {
				for (int y=0;y<parent.getHeight();y++) {
					Color c = robot.getPixelColor(x+parent.getX(),y+parent.getY());					
					if (!paletteUtil.isMHPColor(c)) {
						g.setColor(Color.green);
						g.fillRect(x,y,1,1);	
					}
				}
			}
		}

	}

    */

}
