package novotnyr.mobile.currency;

import java.io.*;

import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import javax.microedition.rms.RecordStore;

public class CurrencyMidlet extends MIDlet 
    implements CommandListener, ItemCommandListener, ItemStateListener
{

    Form form;
    
    TextBox textBox;
    
    Command cmdExit = new Command("Koniec", Command.BACK, 1); 
    Command cmdConvert = new Command("Konvertovať", Command.SCREEN, 2);
    
    TextField txtCurrency = new TextField("Menových jednotiek: ", null, 50, TextField.DECIMAL);
    TextField txtExchangeRate = new TextField("Kurz: ", null, 50, TextField.DECIMAL);
    
    StringItem conversionResult = new StringItem("Cudzie v domácej: ", "");
    StringItem backConversionResult = new StringItem("Domáca v cudzej: ", "");
    
    public CurrencyMidlet() {        
        form = new Form("Konvertor mien");
        form.setItemStateListener(this);
        form.addCommand(cmdExit);    

        form.append(txtCurrency);        
        txtCurrency.addCommand(cmdConvert);        
        txtCurrency.setItemCommandListener(this);
        
        txtExchangeRate.addCommand(cmdConvert);
        txtExchangeRate.setItemCommandListener(this);
        form.append(txtExchangeRate);

        form.append(conversionResult);        
        form.append(backConversionResult);        
       
        form.setCommandListener(this);
    }
    
    protected void startApp() throws MIDletStateChangeException {
        loadSettings();
        Display.getDisplay(this).setCurrent(form);        
    }
    
    protected void pauseApp() {
    }
    
    protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
        storeSettings();
    }
    
    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 currency = Float.valueOf(txtCurrency.getString()).floatValue();
        float exchangeRate = Float.valueOf(txtExchangeRate.getString()).floatValue(); 
        
        String result = "";
        
        if(command.equals(cmdConvert)) {  
            double inForeign = Math.floor(currency * exchangeRate * 100.0f) / 100.0f;
            double inLocal = Math.floor(currency * (1.0 / exchangeRate) * 100.0f) / 100.0f;
            
            conversionResult.setLabel("Cudzie v domácej: ");
            conversionResult.setText(inForeign + "");
            backConversionResult.setLabel("Domáca v cudzej: ");
            backConversionResult.setText(inLocal + "");
        }
    }
    
    public void itemStateChanged(Item item) {
        if(item.equals(txtCurrency) || item.equals(txtExchangeRate)) {
            commandAction(cmdConvert, item);
        }
    }
    
    public void storeSettings() {
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        DataOutputStream os = new DataOutputStream(buffer);
        RecordStore store = null;
        try {
            store = RecordStore.openRecordStore("currencyConverter", true);
            os.writeUTF(txtExchangeRate.getString());

            byte[] bytes = buffer.toByteArray();
            
            if(store.getNumRecords() == 0) {                    
                store.addRecord(bytes, 0, bytes.length);
                System.out.println("Settings saved. (New record created).");
            } else {
                store.setRecord(1, bytes, 0, bytes.length);
                System.out.println("Settings saved. (Old record replaced).");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
               store.closeRecordStore();
               os.close();
            } catch (Exception e2) {
               e2.printStackTrace();
            }
        }        
    }
    
    public void loadSettings() {
        RecordStore store = null;
        DataInputStream in = null;
        try {
            store = RecordStore.openRecordStore("currencyConverter", true);
            byte[] buffer = store.getRecord(1);
            
            in = new DataInputStream(new ByteArrayInputStream(buffer));
            String s = in.readUTF();
            
            System.out.println("Settings retrieved.");
            txtExchangeRate.setString(s);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            } 
        }
    }
}
