package com.marinilli.b2.c5;

import javax.microedition.io.*;
import javax.microedition.midlet.*;
import javax.microedition.rms.*;
import javax.microedition.lcdui.*;
import java.io.*;

/**
 * Chapter 5 - A General Purpose, Simple License Manager
 *
 * @author Mauro Marinilli
 * @version 1.0
 */

public class MIDLicenseManager implements CommandListener {
  private RecordStore keyStore;
  private MIDlet midlet;
  private String licenseId = "";
  private String passwd = "";
  private Form form;
  private TextField idTextField;
  private TextField pwdTextField;
  private final static String SERVER_URL = "http://localhost:8080/license/midp?license-id=";
  private boolean successfullyRegistered = false;
  private Displayable returnDisplayable;

  /**
   *
   */
  public MIDLicenseManager(MIDlet m) {
    midlet = m;
    // Create a new record store for keys for this midlet suite
    try {
      keyStore = RecordStore.openRecordStore("keys", true);
      int items = keyStore.getNumRecords();
      System.out.println("items="+items);
      if (items > 0) {
        String roughLicenseId = new String(keyStore.getRecord(1));
        if (roughLicenseId!=null)
          licenseId = unscramble(roughLicenseId);
        String roughPasswd = new String(keyStore.getRecord(2));
        if (roughPasswd!=null)
          passwd = unscramble(roughPasswd);
      } else {
        // the recordstore has to be initialized
        String n = "";
        keyStore.addRecord(n.getBytes(), 0, n.getBytes().length);
        keyStore.addRecord(n.getBytes(), 0, n.getBytes().length);
      }
    } catch (RecordStoreException rse) {
      System.out.println("MIDLicenseManager() "+rse);
    }
  }

  /**
   *
   */
  public boolean isLicensed() {
    return (licenseId != "");
  }

  /**
   * scrambles a string
   */
  public String scramble(String s) {
    return s;
  }

  /**
   * un-scramble a string
   */
  public String unscramble(String s) {
    return s;
  }

  /**
   * Registering a copy
   */
  public void register(){
    returnDisplayable = Display.getDisplay(midlet).getCurrent();
    if (returnDisplayable==null)
      returnDisplayable = new Form("Hello");
    if (isLicensed()) {

      Form f = new Form("Software Already Licensed");
      f.append("Impossible to register an already registered copy.");
      f.append("Please contact support for help");
      Display.getDisplay(midlet).setCurrent(f);
      f.setCommandListener(this);
      f.addCommand(new Command("back",Command.BACK,1));
      return;
    }

    idTextField = new TextField("Insert Licensed User", "", 12, TextField.ANY);
    pwdTextField = new TextField("Insert License Code", "", 15, TextField.PASSWORD);
    form = new Form("Registration");
    form.append(idTextField);
    form.append(pwdTextField);
    form.addCommand(new Command("ok",Command.OK,1));
    form.setCommandListener(this);
    Display.getDisplay(midlet).setCurrent(form);
  }

  /**
   * connect to the license server
   */
  public String connect() {
    HttpConnection c = null;
    InputStream is = null;
    OutputStream os = null;
    StringBuffer message = new StringBuffer();

    try {
      c = (HttpConnection)Connector.open(createURL());
      String outcome = c.getHeaderField("outcome");
      //in case of no connection return null
      if (outcome==null) {
        return null;
      }

      if (outcome.equals("true"))
        successfullyRegistered = true;
      // open the InputStream
      is = c.openInputStream();
      // read the servlet output
      int ch;
      while ((ch = is.read()) != -1) {
        message.append((char)ch);
      }
    } catch (Exception exc) {
      System.out.println("connect() "+exc);
    }
    return message.toString();
  }

  /**
   * process commands
   */
  public void commandAction(Command c, Displayable d) {
    if (c.getCommandType()==Command.OK) {
      String s = "";
      Gauge gau = new Gauge("Checking License",false,8,0);
      Form frm = new Form("Please Wait.. ",new Item[] {gau});
      gau.setValue(2);
      Display.getDisplay(midlet).setCurrent(frm);
      licenseId= idTextField.getString();
      passwd = pwdTextField.getString();
      gau.setValue(4);
      String msg = connect();
      gau.setValue(6);
      if (msg==null) {
        s = "Connection Unavailable" ;
        msg = "Please try again later.";
        licenseId = "";
        passwd = "";
      } else {
        gau.setValue(8);
        if(successfullyRegistered) {
          save(licenseId, passwd);
          s = "Registration Successful";
        } else {
          licenseId = "";
          passwd = "";
          s = "Invalid License";
        }
      }

      Form f = new Form(s);
      f.append(msg);
      Display.getDisplay(midlet).setCurrent(f);
      f.setCommandListener(this);
      f.addCommand(new Command("back",Command.BACK,1));
    }
    if (c.getCommandType()==Command.BACK) {
      Display.getDisplay(midlet).setCurrent(returnDisplayable);
    }
  }

  /**
   * save data persistently
   */
  private void save(String id, String pwd) {
    try {
      String scrambled = scramble(licenseId);
      keyStore.setRecord(1, scrambled.getBytes(), 0, scrambled.getBytes().length);

      scrambled = scramble(passwd);
      keyStore.setRecord(2, scrambled.getBytes(), 0, scrambled.getBytes().length);
      //close the recordStore
      keyStore.closeRecordStore();
    } catch (RecordStoreException rse) {
      System.out.println("MIDLicenseManager-save() "+rse);
    }
  }

  /**
   * create an URL
   */
  private String createURL(){
    return SERVER_URL + scramble(licenseId) + "&license-pwd=" + scramble(passwd);
  }

}