import javabook.*;
public class Raiz{
    private MainWindow vta;
    public Raiz(int modo,int procesamiento) {
        this.modo = modo;
        if (modo==GUI) vta = new MainWindow();
        this.procesamiento = procesamiento;
    }
    public final static int POSITIVO = 1;
    public final static int IMAGINARIO = 2;
    private int procesamiento =0;
    public int getProcesamiento(){ return procesamiento;}
    public double raiz(double x) throws Exception{
        double resultado =0;
        if (procesamiento == POSITIVO) {
            if(x<0)
                throw new Exception("El numero debe ser positivo");
            else
                resultado= Math.sqrt(x);
        } else if (procesamiento == IMAGINARIO) {
            resultado=Math.sqrt(Math.abs(x));
        }
        return resultado;
    }//raiz
    public final static int TERMINAL = 1;
    public final static int GUI = 2;
    private int modo=0;
    public int getModo() { return modo;}
    public double capturar(){
        double valor =0.0;
        if (modo == TERMINAL) {
            valor= SimpleInput.getDouble();
        } else {
            InputBox in = new InputBox(vta);
            vta.show();
            valor=in.getDouble();
        }
        return valor;
    }
    public void desplegar(String msg) {
        if (modo==TERMINAL)
            System.out.println(msg);
        else if (modo==GUI) {
            OutputBox out = new OutputBox(vta);
            out.printLine(msg);
            out.show();
        }
        
    }
    public void error(String msg) {
        if ( modo==TERMINAL) {
            System.err.println(msg);
        } else if (modo==GUI) {
            MessageBox out = new MessageBox(vta);
            out.show(msg);
        }
    }
    public void operacion(){
        double x;
        try{
            x = this.capturar();
            double y= this.raiz(x);
            String msg ="";
            if (procesamiento == IMAGINARIO && x<0) 
                msg = "j" + y;
            else 
                msg = msg + y;
            this.desplegar("El resultado es: "+ msg);
        }//try
        catch (Exception e){
            this.error("Numero negativo");
        }//catch
    }//operacion
    
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Raiz rz = new Raiz(Raiz.GUI,Raiz.IMAGINARIO);
        rz.operacion();
        
    }//main
    
}
