/*
 * Created on Aug 17, 2004
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package hibergui.property;

import static hibergui.HiberGUI.*;
import hibergui.Edit;
import hibergui.Form;
import hibergui.I18n;
import hibergui.verify.SelfConstraint;
import hibergui.verify.VerificationError;

import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Text;

/**
 * @author espakm
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public abstract class TextEdit<T> extends Edit<T> {
    
    private Text txt;
    
    public TextEdit(Form form, Composite cptParent, int style, String prop, String name) {
        super(form, cptParent, style, prop, name);
        
        txt.addModifyListener(lsn_WIDGET_MOD);
        txt.addKeyListener(lsn_WIDGET_KEY);
        txt.addFocusListener(lsn_WIDGET_FOCUS);
        txt.addTraverseListener(lsn_TRAVERSE);
        
        if ((style & NOT_NULL) != 0)
        	addConstraint(
        			new SelfConstraint(){
        				public boolean check() {
        					return !txt.getText().equals("");
        				}
        			},
        			new VerificationError(
        					I18n.get("constraint.notnull.0") + 
        					getName() + 
        					I18n.get("constraint.notnull.2"))
        	);
    }
    
	@Override
    protected Control createContents(Composite cptParent) {
    	boolean multi = (style & MULTI) != 0;
        return txt = new Text(
        		cptParent, 
        		SWT.BORDER |
        		(multi? (SWT.MULTI | SWT.WRAP): SWT.SINGLE));
    }

	public int getLineHeight() {
		return txt.getLineHeight();
	}

	@Override
	public void clear() {
        txt.setText("");
    }
    
    protected String getText() {
        String s = txt.getText();
        if (s.length() == 0)// && ((style & NOT_NULL) == 0))
        	return null;
        return s;
    }
    
    protected void setText(String s) {
        if (s == null)
        	s = "";
        txt.setText(s);
    }
    
	@Override
    public boolean setFocus() {
        return txt.forceFocus();
    }
    
	@Override
    public boolean isEnabled() {
        return txt.isEnabled();
    }

	// TODO: just for debug purposes
	public boolean isVisible() {
		return txt.isVisible();
	}
	
	@Override
    public void setEnabled(boolean b) {
        txt.setEnabled(b);
    }
    
	@Override
	public void setEditable(boolean b) {
		txt.setEditable(b);
	}
	
	@Override
    public void setBackground(Color clr) {
    	txt.setBackground(clr);
    }
}
