/*
 * Created on 24.02.2005
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package de.farafin.snEADy.control.GaphixStuff;

import java.awt.Graphics;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.VolatileImage;

/**
 * @author larsonmars
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class GrTextField extends GrTextArea{
	
	
	private boolean carr;
	private boolean numbersOnly;
	private String comm;
	private GrTextField troot;
	public GrTextField(int x,int y,int maxC,String initText,int allig,boolean onlyNumbers,String command){
		this(x,y,maxC,1,initText,allig,onlyNumbers,command);
	}
	public GrTextField(int x,int y,int maxC,int maxL,String initText,int allig,boolean onlyNumbers,String command){
		super(x,y,maxC*8,maxL*14,initText,allig,true);
		troot=this;
		comm=command;
		numbersOnly=onlyNumbers;
		addFocusListener(new FocusListener(){
			public void focusLost(FocusEvent e){
				carr=false;
				if (comm!=null)C_GraphixData.main.control(comm + text.toString());
				action();
				repaint();
			}
			public void focusGained(FocusEvent e){
				carr=true;
				repaint();
			}
		});
		addKeyListener(new KeyListener(){
			public void keyTyped(KeyEvent e){
				int c=e.getKeyChar();

				if (text.length()<text.capacity() && c>' ' && c<='~'){
					if (!numbersOnly || (c>='0' && c<='9')){
						text.append(e.getKeyChar());
						repaint();
					}
				}
			}
			public void keyPressed(KeyEvent e){
				int c=e.getKeyCode();
				switch(c){
				case KeyEvent.VK_BACK_SPACE:
					if (text.length()>0)text.deleteCharAt(text.length()-1);
					repaint();
					break;
				case KeyEvent.VK_ENTER:
					if (comm!=null)C_GraphixData.main.control(comm + text.toString());
					action();
					troot.getFocusCycleRootAncestor().requestFocus();
					repaint();
					break;
				}
			}
			public void keyReleased(KeyEvent e){
				
			}
		});

		
		
	}
	
	private void renderText(){
		Graphics g;
		String drawT;
		if (carr)
			drawT=text.toString() + (char)127;
		else
			drawT=text.toString();
		
		do{
    		if (img_text.validate(C_GraphixData.gc)==VolatileImage.IMAGE_INCOMPATIBLE){
    			img_text=C_GraphixTools.createBackBufferVI(showW,showH);
    		}
    		g=img_text.getGraphics();
    		if (drawMode==F_MARKED)
    			g.setColor(COL_BLUE2);
    		else
    			g.setColor(COL_BLUE1);
    		
    		g.fillRect(0,0,showW,showH);
    		if (alligment==ALLIG_LEFT)
    			C_GraphixTools.drawBitmapString(drawT,0,0,M_FONTSERP8X14,g,ALLIG_LEFT,drawMode);
    		else
    			C_GraphixTools.drawBitmapString(drawT,showW,0,M_FONTSERP8X14,g,ALLIG_RIGHT,drawMode);
		}while(img_text.contentsLost());
	
	}

	public void repaint(){
		renderText();
		paint(getGraphics());
	}
	
}
