/** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.zip_picker);

    LoggerManager.setLoggerFactory(new AndroidLoggerFactory());

    logger = (AndroidLogger) LoggerManager.getLogger(this.getClass().getName());
    // enable toasts for info level logging.  toasts are default for error and warnings.
    logger.setToastContext(getBaseContext());
    logger.setInfoToastEnabled(true);

    Button createButton = (Button) findViewById(R.id.SignButton);
    createButton.setOnClickListener(
        new OnClickListener() {
          public void onClick(View view) {
            invokeZipSignerActivity();
          }
        });

    String extStorageDir = Environment.getExternalStorageDirectory().toString();
    // Strip /mnt from /sdcard
    if (extStorageDir.startsWith("/mnt/sdcard")) extStorageDir = extStorageDir.substring(4);

    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    String inputFile = prefs.getString(PREFERENCE_IN_FILE, extStorageDir + "/unsigned.zip");
    String outputFile = prefs.getString(PREFERENCE_OUT_FILE, extStorageDir + "/signed.zip");
    int keyIndex = prefs.getInt(PREFERENCE_KEY_INDEX, 0);

    EditText inputText = (EditText) findViewById(R.id.InFileEditText);
    inputText.setText(inputFile);

    EditText outputText = (EditText) findViewById(R.id.OutFileEditText);
    outputText.setText(outputFile);

    Button button = (Button) findViewById(R.id.OpenPickButton);
    button.setOnClickListener(
        new View.OnClickListener() {
          public void onClick(View arg0) {
            pickInputFile();
          }
        });

    button = (Button) findViewById(R.id.SaveAsPickButton);
    button.setOnClickListener(
        new View.OnClickListener() {
          public void onClick(View arg0) {
            pickOutputFile();
          }
        });

    button = (Button) findViewById(R.id.InOutPickButton);
    button.setOnClickListener(
        new View.OnClickListener() {
          public void onClick(View arg0) {
            pickInputOutputFiles();
          }
        });

    Spinner spinner = (Spinner) findViewById(R.id.KeyModeSpinner);
    keyModeSpinnerAdapter =
        KeyListSpinnerAdapter.createInstance(this, android.R.layout.simple_spinner_item);
    keyModeSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(keyModeSpinnerAdapter);
    if (keyIndex >= keyModeSpinnerAdapter.getCount()) keyIndex = 0;
    spinner.setSelection(keyIndex);
    spinner.setOnItemSelectedListener(
        new AdapterView.OnItemSelectedListener() {
          @Override
          public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
            SharedPreferences.Editor editor = prefs.edit();
            editor.putInt(PREFERENCE_KEY_INDEX, position);
            editor.commit();
            updateAlgorithmSpinner(position);
          }

          @Override
          public void onNothingSelected(AdapterView<?> adapter) {}
        });

    algorithmSpinner = (Spinner) findViewById(R.id.CertSignatureAlgorithm);
    sha1WithRsaSpinnerAdapter =
        ArrayAdapter.createFromResource(
            this, R.array.Sha1WithRsaAlgorithmArray, android.R.layout.simple_spinner_item);
    sha1WithRsaSpinnerAdapter.setDropDownViewResource(
        android.R.layout.simple_spinner_dropdown_item);
    allAlgorithmsSpinnerAdapter =
        ArrayAdapter.createFromResource(
            this, R.array.AllShaWithRsaAlgorithmsArray, android.R.layout.simple_spinner_item);
    allAlgorithmsSpinnerAdapter.setDropDownViewResource(
        android.R.layout.simple_spinner_dropdown_item);

    updateAlgorithmSpinner(keyIndex);

    algorithmSpinner.setOnItemSelectedListener(
        new AdapterView.OnItemSelectedListener() {
          @Override
          public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
            if (algorithmSpinnerAdapter.getCount() > 1) {
              SharedPreferences.Editor editor = prefs.edit();
              editor.putInt(PREFERENCE_ALG_INDEX, position);
              editor.commit();
            }
          }

          @Override
          public void onNothingSelected(AdapterView<?> adapter) {}
        });
  }
  /** Receives the result of other activities started with startActivityForResult(...) */
  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    Uri uri;

    switch (resultCode) {
      case RESULT_OK:
        switch (requestCode) {
          case REQUEST_CODE_PICK_FILE_TO_OPEN:
            // obtain the filename
            uri = data == null ? null : data.getData();
            if (uri != null) {
              ((EditText) findViewById(R.id.InFileEditText)).setText(uri.getPath());
            }
            break;
          case REQUEST_CODE_PICK_FILE_TO_SAVE:
            // obtain the filename
            uri = data == null ? null : data.getData();
            if (uri != null) {
              ((EditText) findViewById(R.id.OutFileEditText)).setText(uri.getPath());
            }
            break;
          case REQUEST_CODE_PICK_INOUT_FILE:
            // obtain the filename
            uri = data == null ? null : data.getData();
            if (uri != null) {
              String filename = uri.getPath();
              ((EditText) findViewById(R.id.InFileEditText)).setText(filename);
              // auto set output file ... "input.zip" becomes "input-signed.zip"
              int pos = filename.lastIndexOf('.');
              if (pos > 0) {
                filename = filename.substring(0, pos) + "-signed" + filename.substring(pos);
              }
              ((EditText) findViewById(R.id.OutFileEditText)).setText(filename);
            }
            break;
          case REQUEST_CODE_SIGN_FILE:
            logger.info(getResources().getString(R.string.FileSigningSuccess));
            break;
          case REQUEST_CODE_MANAGE_KEYS:
            keyModeSpinnerAdapter.changeData();
            break;
          default:
            logger.error("onActivityResult, RESULT_OK, unknown requestCode " + requestCode);
            break;
        }
        break;
      case RESULT_CANCELED: // signing operation canceled
        switch (requestCode) {
          case REQUEST_CODE_SIGN_FILE:
            logger.info(getResources().getString(R.string.FileSigningCancelled));
            break;
          case REQUEST_CODE_PICK_FILE_TO_OPEN:
            break;
          case REQUEST_CODE_PICK_FILE_TO_SAVE:
            break;
          case REQUEST_CODE_PICK_INOUT_FILE:
            break;
          case REQUEST_CODE_MANAGE_KEYS:
            keyModeSpinnerAdapter.changeData();
            break;
          default:
            logger.error("onActivityResult, RESULT_CANCELED, unknown requestCode " + requestCode);
            break;
        }
        break;
      case RESULT_FIRST_USER: // error during signing operation
        switch (requestCode) {
          case REQUEST_CODE_SIGN_FILE:
            // ZipSignerActivity displays a toast upon exiting with an error, so we probably don't
            // need to do this.
            String errorMessage = data.getStringExtra("errorMessage");
            logger.debug("Error during file signing: " + errorMessage);
            break;
          default:
            logger.error("onActivityResult, RESULT_FIRST_USER, unknown requestCode " + requestCode);
            break;
        }
        break;
      case RESULT_FIRST_USER + 1: // error with auto-key selection
        switch (requestCode) {
          case REQUEST_CODE_SIGN_FILE:
            // TODO display alert dialog?
            // String errorMessage = data.getStringExtra("errorMessage");
            String errorMessage =
                String.format(
                    getResources().getString(R.string.KeySelectionMessage), getInputFilename());
            AlertDialogUtil.alertDialog(
                this, getResources().getString(R.string.KeySelectionError), errorMessage);
            break;
          default:
            logger.error(
                "onActivityResult, RESULT_FIRST_USER+1, unknown requestCode " + requestCode);
            break;
        }
        break;
      default:
        logger.error(
            "onActivityResult, unknown resultCode "
                + resultCode
                + ", requestCode = "
                + requestCode);
    }
  }