package novotnyr.mobile.temperature;

import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;

public class TemperatureMidlet extends MIDlet implements CommandListener, ItemCommandListener {
    TextBox textBox;
    
    Command cmdExit = new Command("Koniec", Command.BACK, 1);;   
    
    Command cmdConvertToFahrenheit = new Command("°C na F", Command.SCREEN, 2);
    Command cmdConvertToCelsius = new Command("F na °C", Command.SCREEN, 2);
    
    Form form;
    
    TextField txtTemperature = new TextField("Teplota", null, 50, TextField.NUMERIC);
    StringItem conversionResult = new StringItem("Výsledok: ", "");
    
    public TemperatureMidlet() {
        
        form = new Form("Konvertor teplôt");
        form.append("Zadajte teplotu vo Fahrenheitoch alebo v stupòoch Celzia");
        form.append(txtTemperature);

        form.addCommand(cmdExit);    
        
        txtTemperature.addCommand(cmdConvertToCelsius);
        txtTemperature.addCommand(cmdConvertToFahrenheit);
        
        txtTemperature.setItemCommandListener(this);
        
        form.append(conversionResult);        
       
        form.setCommandListener(this);
    }
    
    protected void startApp() throws MIDletStateChangeException {
        Display.getDisplay(this).setCurrent(form);        
    }
    
    protected void pauseApp() {
    }
    
    protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
    }
    
    
    public void commandAction(Command command, Displayable displayable) {
        if (command.equals(cmdExit)) {
            try {
                destroyApp(true);
                notifyDestroyed();
            } catch (Exception e) {
                //nothing
            }
        }
    }
    
    
    public void commandAction(Command command, Item item) {
        float degrees = Integer.valueOf(txtTemperature.getString()).floatValue();        
        String result = "";
        
        if(command.equals(cmdConvertToFahrenheit)) {            
            result = new Float(((9.0 /5.0) * degrees) + 32).toString();
            conversionResult.setText(result + " F");
        }
        
        if(command.equals(cmdConvertToCelsius)) {           
            result = new Float((5.0 /9.0) * (degrees - 32)).toString();
            conversionResult.setText(result + " °C");
        }           
    }
}
