/**
   * Initializes variables and widgets of the activity. The saveInstanceState bundle has always all
   * the configurations. And if the activity is created to modify a configuration it also has the
   * position of the configuration the user wish to update
   */
  @Override
  @SuppressWarnings("unchecked")
  protected void onCreate(Bundle savedInstanceState) {
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.ly_new_configuration);

    inflater = this.getLayoutInflater();
    configurations = new ArrayList<DeviceConfiguration>();
    configurations =
        (ArrayList<DeviceConfiguration>)
            getIntent().getExtras().getSerializable(ConfigurationsActivity.KEY_CONFIGURATIONS);

    // CREATES AND SETS DEFAULT VALUES FOR THE NEW CONFIGURATION
    newConfiguration = new DeviceConfiguration(this);
    newConfiguration.setVisualizationFrequency(DEFAULT_RECEPTION_FREQ);
    newConfiguration.setSamplingFrequency(DEFAULT_SAMPLING_FREQ);
    newConfiguration.setNumberOfBits(DEFAULT_NUMBER_OF_BITS);

    // GETS ALL THE VIEWS
    receptionfreqSeekbar = (SeekBar) findViewById(R.id.nc_reception_seekbar);
    samplingfreqSeekbar = (SeekBar) findViewById(R.id.nc_sampling_seekbar);
    receptionFreqEditor = (EditText) findViewById(R.id.nc_reception_freq_view);
    samplingFreqEditor = (EditText) findViewById(R.id.nc_sampling_freq_view);
    configurationName = (EditText) findViewById(R.id.dev_name);
    macAddress = (EditText) findViewById(R.id.nc_mac_address);
    activeChannelsTV = (TextView) findViewById(R.id.nc_txt_active_channels);
    displayChannelsTV = (TextView) findViewById(R.id.nc_txt_channels_to_show);

    // INIT SEEKBARS AND EDITORS TO DEFAULT STATE
    receptionfreqSeekbar.setOnSeekBarChangeListener(
        new OnSeekBarChangeListener() {
          public void onProgressChanged(SeekBar seekBar, int progress, boolean changedByUser) {
            if (changedByUser) {
              int valueToChangeRounded =
                  ALLOW_RECEPTION_FREQ.floor(progress + 1) - RECEPTION_FREQ_MIN;
              Log.i(
                  "TRYANDROID", "samplingprogress " + progress + " floor:" + valueToChangeRounded);

              receptionFreqEditor.setText(
                  String.valueOf(valueToChangeRounded + RECEPTION_FREQ_MIN));
              newConfiguration.setVisualizationFrequency(valueToChangeRounded + RECEPTION_FREQ_MIN);
            }
          }
          // needed for the listener
          public void onStartTrackingTouch(SeekBar seekBar) {}

          public void onStopTrackingTouch(SeekBar seekBar) {}
        });

    receptionFreqEditor.setOnEditorActionListener(
        new OnEditorActionListener() {
          @Override
          public boolean onEditorAction(
              TextView receptionFreqEditorTextView, int actionId, KeyEvent event) {
            boolean handled = false;

            if (actionId == EditorInfo.IME_ACTION_DONE) {
              String frequencyString = receptionFreqEditorTextView.getText().toString();
              if (frequencyString.compareTo("") == 0) frequencyString = "0";
              int newFrequency = Integer.parseInt(frequencyString);

              setReceptionFrequency(newFrequency);
              closeKeyboardAndClearFocus();
              handled = true;
            }
            return handled;
          }

          private void setReceptionFrequency(int newFrequency) {
            // accepted frequency
            if (newFrequency >= RECEPTION_FREQ_MIN && newFrequency <= RECEPTION_FREQ_MAX) {
              receptionfreqSeekbar.setProgress((newFrequency - RECEPTION_FREQ_MIN));
              newConfiguration.setVisualizationFrequency(newFrequency);
              // frequency introduced is too big
            } else if (newFrequency > RECEPTION_FREQ_MAX) {
              receptionfreqSeekbar.setProgress(RECEPTION_FREQ_MAX);
              receptionFreqEditor.setText(String.valueOf(RECEPTION_FREQ_MAX));
              newConfiguration.setVisualizationFrequency(RECEPTION_FREQ_MAX);
              displayErrorToast(
                  getString(R.string.nc_error_max_frequency) + " " + RECEPTION_FREQ_MAX + "Hz");
              // frequency introduced is too small
            } else {
              receptionfreqSeekbar.setProgress(0);
              receptionFreqEditor.setText(String.valueOf(RECEPTION_FREQ_MIN));
              newConfiguration.setVisualizationFrequency(RECEPTION_FREQ_MIN);
              displayErrorToast(
                  getString(R.string.nc_error_min_frequency) + " " + RECEPTION_FREQ_MIN + " Hz");
            }
          }

          private void closeKeyboardAndClearFocus() {
            receptionFreqEditor.clearFocus();
            InputMethodManager inputManager =
                (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            inputManager.hideSoftInputFromWindow(
                getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
          }
        });

    samplingfreqSeekbar.setOnSeekBarChangeListener(
        new OnSeekBarChangeListener() {
          public void onProgressChanged(SeekBar seekBar, int progress, boolean changedByUser) {
            if (changedByUser) {
              samplingFreqEditor.setText(String.valueOf(progress + SAMPLING_FREQ_MIN));
              newConfiguration.setSamplingFrequency(progress + SAMPLING_FREQ_MIN);
            }
          }
          // needed for the listener
          public void onStartTrackingTouch(SeekBar seekBar) {}

          public void onStopTrackingTouch(SeekBar seekBar) {}
        });

    samplingFreqEditor.setOnEditorActionListener(
        new OnEditorActionListener() {
          @Override
          public boolean onEditorAction(TextView currentView, int actionId, KeyEvent event) {
            boolean handled = false;

            if (actionId == EditorInfo.IME_ACTION_DONE) {
              String frequencyString = currentView.getText().toString();
              if (frequencyString.compareTo("") == 0) frequencyString = "0";
              int newFrequency = Integer.parseInt(frequencyString);

              setFrequency(newFrequency);
              closeKeyboardAndClearFocus();
              handled = true;
            }
            return handled;
          }

          private void setFrequency(int newFrequency) {
            // accepted frequency
            if (newFrequency >= SAMPLING_FREQ_MIN && newFrequency <= SAMPLING_FREQ_MAX) {
              samplingfreqSeekbar.setProgress((newFrequency - SAMPLING_FREQ_MIN));
              newConfiguration.setSamplingFrequency(newFrequency);
              // frequency introduced is too big
            } else if (newFrequency > SAMPLING_FREQ_MAX) {
              samplingfreqSeekbar.setProgress(SAMPLING_FREQ_MAX);
              samplingFreqEditor.setText(String.valueOf(SAMPLING_FREQ_MAX));
              newConfiguration.setSamplingFrequency(SAMPLING_FREQ_MAX);
              displayErrorToast(
                  getString(R.string.nc_error_max_frequency) + " " + SAMPLING_FREQ_MAX + "Hz");
              // frequency introduced is too small
            } else {
              samplingfreqSeekbar.setProgress(0);
              samplingFreqEditor.setText(String.valueOf(SAMPLING_FREQ_MIN));
              newConfiguration.setSamplingFrequency(SAMPLING_FREQ_MIN);
              displayErrorToast(
                  getString(R.string.nc_error_min_frequency) + " " + SAMPLING_FREQ_MIN + " Hz");
            }
          }

          private void closeKeyboardAndClearFocus() {
            samplingFreqEditor.clearFocus();
            InputMethodManager inputManager =
                (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            inputManager.hideSoftInputFromWindow(
                getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
          }
        });

    /* ********* UPDATE CONFIGURATION CODE ********* */
    if (getIntent().getExtras().containsKey(ConfigurationsActivity.KEY_CONFIGURATION_POSITION))
      isUpdatingConfiguration = true;

    if (isUpdatingConfiguration) {
      oldConfiguration =
          configurations.get(
              getIntent().getExtras().getInt(ConfigurationsActivity.KEY_CONFIGURATION_POSITION));
      // FILL WIDGETS FIELDS WITH CONFIGURATION TO EDIT DETAILS
      configurationName.setText(oldConfiguration.getName());
      macAddress.setText(oldConfiguration.getMacAddress());
      receptionfreqSeekbar.setProgress(
          oldConfiguration.getVisualizationFrequency() - RECEPTION_FREQ_MIN);
      receptionFreqEditor.setText(String.valueOf(oldConfiguration.getVisualizationFrequency()));
      samplingfreqSeekbar.setProgress(oldConfiguration.getSamplingFrequency());
      samplingFreqEditor.setText(String.valueOf(oldConfiguration.getSamplingFrequency()));
      activeChannelsTV.setVisibility(View.VISIBLE);
      activeChannelsTV.setText(
          getString(R.string.nc_channels_to_activate) + " " + oldConfiguration.getActiveChannels());
      displayChannelsTV.setVisibility(View.VISIBLE);
      displayChannelsTV.setText(oldConfiguration.getDisplayChannelsWithSensors());

      // MODIFY VARIABLES FOR VALIDATION PURPOSES
      activeChannels = oldConfiguration.getActiveSensors();
      boolean[] boolArray = {true};
      channelsSelected = boolArray;
      configurations.remove(
          configurations.get(
              getIntent().getExtras().getInt(ConfigurationsActivity.KEY_CONFIGURATION_POSITION)));
      newConfiguration = oldConfiguration;
    }
  }
  /**
   * Validates all the configuration fields. Returns false if an error is encountered and true
   * otherwise
   */
  private boolean validateFields() {
    boolean validated = true;

    // VALIDATE NAME FIELD ALREADY EXISTS
    for (DeviceConfiguration c : configurations) {
      if (c.getName().compareTo(configurationName.getText().toString()) == 0) {
        configurationName.setError(getString(R.string.nc_error_message_name_duplicate));
        configurationName.requestFocus();
        validated = false;
      }
    }

    // VALIDATE NAME FIELD IS NOT NULL
    if (configurationName.getText().toString() == null
        || configurationName.getText().toString().compareTo("") == 0) {
      configurationName.setError(getString(R.string.nc_error_message_name_null));
      configurationName.requestFocus();
      validated = false;
    }

    // VALIDATE MAC FIELD
    String macSyntax = "^([0-9A-F]{2}[:-]){5}([0-9A-F]{2})$";
    if (macAddress.getText().toString() == null
        || macAddress.getText().toString().compareTo("") == 0
        || !macAddress.getText().toString().matches(macSyntax)
            && macAddress.getText().toString().compareTo("test") != 0) {
      macAddress.setError(getString(R.string.nc_error_message_mac));
      if (validated) {
        macAddress.requestFocus();
      }
      validated = false;
    }

    // VALIDATE RECEPTION FREQUENCY
    if (receptionFreqEditor.getText().toString() == null
        || receptionFreqEditor.getText().toString().compareTo("") == 0
        || Integer.parseInt(receptionFreqEditor.getText().toString()) < RECEPTION_FREQ_MIN
        || Integer.parseInt(receptionFreqEditor.getText().toString()) > RECEPTION_FREQ_MAX) {
      receptionFreqEditor.setError("invalid frequency");
      if (validated) {
        receptionFreqEditor.requestFocus();
      }
      validated = false;
    }

    // VALIDATE SAMPLING FREQUENCY
    if (samplingFreqEditor.getText().toString() == null
        || receptionFreqEditor.getText().toString().compareTo("") == 0
        || Integer.parseInt(samplingFreqEditor.getText().toString()) < SAMPLING_FREQ_MIN
        || Integer.parseInt(samplingFreqEditor.getText().toString()) > SAMPLING_FREQ_MAX) {
      samplingFreqEditor.setError("invalid frequency");
      if (validated) {
        samplingFreqEditor.requestFocus();
      }
      validated = false;
    }

    // VALIDATE ACTIVE CHANNELS
    if (activeChannels == null || noChannelsActivated(activeChannels)) {
      activeChannelsTV.setError("");
      activeChannelsTV.setTextColor(Color.RED);
      activeChannelsTV.setVisibility(View.VISIBLE);
      activeChannelsTV.setText(getString(R.string.nc_error_message_active_channels) + "  ");
      validated = false;
    }

    // VALIDATE CHANNELS TO DISPLAY
    if (channelsSelected == null || numberOfChannelsSelected(channelsSelected) == 0) {
      displayChannelsTV.setError("");
      displayChannelsTV.setTextColor(Color.RED);
      displayChannelsTV.setVisibility(View.VISIBLE);
      displayChannelsTV.setText(getString(R.string.nc_error_message_channels_to_display) + "  ");
      validated = false;
    }
    return validated;
  }