/*
 * Copyright (C) 2009 University of Washington
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */

package org.odk.collect.android.widgets;

import android.content.Context;
import android.graphics.Typeface;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.AppCompatRadioButton;
import android.support.v7.widget.SwitchCompat;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.util.TypedValue;
import android.view.inputmethod.InputMethodManager;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;

import org.javarosa.core.model.SelectChoice;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.model.data.SelectOneData;
import org.javarosa.core.model.data.helper.Selection;
import org.javarosa.form.api.FormEntryCaption;
import org.javarosa.form.api.FormEntryPrompt;
import org.javarosa.xpath.expr.XPathFuncExpr;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.external.ExternalDataUtil;
import org.odk.collect.android.external.ExternalSelectChoice;
import org.odk.collect.android.views.MediaLayout;

import java.util.ArrayList;
import java.util.Vector;

/**
 * SelectOneWidgets handles select-one fields using radio buttons.
 *
 * @author Carl Hartung (carlhartung@gmail.com)
 * @author Yaw Anokwa (yanokwa@gmail.com)
 */
public class SelectOneWidget extends QuestionWidget implements
    OnCheckedChangeListener {

  private static final String SWITCH_APPEARANCE = "switch";
  /**
   * The position of the item representing the on state of the switch.
   */
  private static final int SWITCH_ON = 0;
  /**
   * The position of the item representing the off state of the switch.
   */
  private static final int SWITCH_OFF = 1;
  private Vector<SelectChoice> mItems; // may take a while to compute
  private ArrayList<CompoundButton> buttons;
  private SwitchCompat switchCompat;

  /**
   * @param context
   *     the Context in which the View will be inflated.
   * @param prompt
   *     the FormEntryPrompt for this View.
   */
  public SelectOneWidget(Context context, FormEntryPrompt prompt) {
    super(context, prompt);

    // SurveyCTO-added support for dynamic select content (from .csv files)
    final String appearanceHint = prompt.getAppearanceHint();
    XPathFuncExpr xPathFuncExpr = ExternalDataUtil.getSearchXPathExpression(appearanceHint);
    if (xPathFuncExpr != null) {
      mItems = ExternalDataUtil.populateExternalChoices(prompt, xPathFuncExpr);
    } else {
      mItems = prompt.getSelectChoices();
    }
    buttons = new ArrayList<>();

    final boolean useSwitch = isSwitch();

    // Layout holds the vertical list of buttons
    LinearLayout buttonLayout = new LinearLayout(context);

    String s = null;
    if (prompt.getAnswerValue() != null) {
      s = ((Selection) prompt.getAnswerValue().getValue()).getValue();
    }

    if (mItems != null) {
      if (useSwitch) {
        switchCompat = new SwitchCompat(context);
        String promptText = prompt.getLongText();
        //switchCompat.setText(promptText == null ? "" : promptText);
        switchCompat.setChecked(mItems.get(0).getValue().equals(s));
        switchCompat.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.question_text));
        switchCompat.setTag(Integer.valueOf(0));
        switchCompat.setId(QuestionWidget.newUniqueId());
        switchCompat.setEnabled(!prompt.isReadOnly());
        switchCompat.setFocusable(!prompt.isReadOnly());
        switchCompat.setTypeface(null, Typeface.NORMAL);
        switchCompat.setHint(prompt.getHelpText());
        final int questionColor = ContextCompat.getColor(context, R.color.question_text);
        final int helpColor = ContextCompat.getColor(context, R.color.hint_text);
        final SpannableStringBuilder switchTextBuilder = new SpannableStringBuilder();
        final boolean hasQuestionText = promptText != null;
        if (!hasQuestionText) {
          promptText = "";
        }
        switchTextBuilder.append(promptText);
        String helpText = prompt.getHelpText();
        final boolean hasHelpText = helpText != null;
        if (hasHelpText && hasQuestionText) {
          switchTextBuilder.append("\n");
        }
        if (!hasHelpText) {
          helpText = "";
        }

        switchTextBuilder.append(helpText);
        final int questionTextLength = promptText.length();
        switchTextBuilder.setSpan(new ForegroundColorSpan(questionColor), 0, questionTextLength, Spanned
            .SPAN_EXCLUSIVE_EXCLUSIVE);
        switchTextBuilder.setSpan(new ForegroundColorSpan(helpColor), questionTextLength, switchTextBuilder.length(),
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        switchCompat.setText(switchTextBuilder);

        buttons.add(switchCompat);
        String audioURI = null;
        audioURI = prompt.getSpecialFormSelectChoiceText(mItems.get(0),
            FormEntryCaption.TEXT_FORM_AUDIO);

        String imageURI;
        if (mItems.get(0) instanceof ExternalSelectChoice) {
          imageURI = ((ExternalSelectChoice) mItems.get(0)).getImage();
        } else {
          imageURI = prompt.getSpecialFormSelectChoiceText(mItems.get(0), FormEntryCaption.TEXT_FORM_IMAGE);
        }

        String videoURI = null;
        videoURI = prompt.getSpecialFormSelectChoiceText(mItems.get(0),
            "video");

        String bigImageURI = null;
        bigImageURI = prompt.getSpecialFormSelectChoiceText(mItems.get(0), "big-image");

        MediaLayout mediaLayout = new MediaLayout(getContext());
        mediaLayout.setAVT(prompt.getIndex(), "." + 0, switchCompat, audioURI, imageURI, videoURI, bigImageURI);

        buttonLayout.addView(mediaLayout);
      } else {
        for (int i = 0; i < mItems.size(); i++) {
          AppCompatRadioButton r = new AppCompatRadioButton(getContext());
          r.setText(prompt.getSelectChoiceText(mItems.get(i)));
          r.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.answer_text));
          r.setTag(Integer.valueOf(i));
          r.setId(QuestionWidget.newUniqueId());
          r.setEnabled(!prompt.isReadOnly());
          r.setFocusable(!prompt.isReadOnly());
          r.setTypeface(null, Typeface.NORMAL);
          r.setTextColor(ContextCompat.getColor(context, R.color.primary_text));
          buttons.add(r);

          if (mItems.get(i).getValue().equals(s)) {
            r.setChecked(true);
          }

          r.setOnCheckedChangeListener(this);

          String audioURI = null;
          audioURI = prompt.getSpecialFormSelectChoiceText(mItems.get(i),
              FormEntryCaption.TEXT_FORM_AUDIO);

          String imageURI;
          if (mItems.get(i) instanceof ExternalSelectChoice) {
            imageURI = ((ExternalSelectChoice) mItems.get(i)).getImage();
          } else {
            imageURI = prompt.getSpecialFormSelectChoiceText(mItems.get(i), FormEntryCaption.TEXT_FORM_IMAGE);
          }

          String videoURI = null;
          videoURI = prompt.getSpecialFormSelectChoiceText(mItems.get(i),
              "video");

          String bigImageURI = null;
          bigImageURI = prompt.getSpecialFormSelectChoiceText(
              mItems.get(i), "big-image");

          MediaLayout mediaLayout = new MediaLayout(getContext());
          mediaLayout.setAVT(prompt.getIndex(), "." + Integer.toString(i), r, audioURI, imageURI,
              videoURI, bigImageURI);

          buttonLayout.addView(mediaLayout);
        }
      }
    }
    buttonLayout.setOrientation(LinearLayout.VERTICAL);

    // The buttons take up the right half of the screen
    LayoutParams buttonParams = new LayoutParams(LayoutParams.MATCH_PARENT,
        LayoutParams.WRAP_CONTENT);
    addView(buttonLayout, buttonParams);
  }

  @Override
  void onHelpClick() {
    if (switchCompat != null && isSwitch()) {
      switchCompat.performClick();
    }
  }

  @Override
  boolean showQuestion() {
    return !isSwitch();
  }

  @Override
  boolean showHelp() {
    return !isSwitch();
  }

  private boolean isSwitch() {
    final String appearanceHint = getPrompt().getAppearanceHint();
    return appearanceHint != null && appearanceHint.equalsIgnoreCase(SWITCH_APPEARANCE);
  }

  @Override
  public void clearAnswer() {
    for (CompoundButton button : this.buttons) {
      if (button.isChecked()) {
        button.setChecked(false);
        return;
      }
    }
  }

  @Override
  public IAnswerData getAnswer() {
    int i = getCheckedId();
    if (i == -1) {
      return null;
    } else {
      SelectChoice sc = mItems.elementAt(i);
      return new SelectOneData(new Selection(sc));
    }
  }

  @Override
  public void setFocus(Context context) {
    // Hide the soft keyboard if it's showing.
    InputMethodManager inputManager = (InputMethodManager) context
        .getSystemService(Context.INPUT_METHOD_SERVICE);
    inputManager.hideSoftInputFromWindow(this.getWindowToken(), 0);
  }

  /**
   * @return the ID of the checked View.
   */
  public int getCheckedId() {
    if (switchCompat == null) {

      for (int i = 0; i < buttons.size(); ++i) {
        CompoundButton button = buttons.get(i);
        if (button.isChecked()) {
          return i;
        }
      }
    } else {
      return switchCompat.isChecked() ? SWITCH_ON : SWITCH_OFF;
    }
    return -1;
  }

  @Override
  public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    if (!isChecked) {
      // If it got unchecked, we don't care.
      return;
    }

    for (CompoundButton button : buttons) {
      if (button.isChecked() && !(buttonView == button)) {
        button.setChecked(false);
      }
    }

    Collect.getInstance().getActivityLogger().logInstanceAction(this, "onCheckedChanged",
        mItems.get((Integer) buttonView.getTag()).getValue(), mPrompt.getIndex());
  }

  @Override
  public void setOnLongClickListener(OnLongClickListener l) {
    for (CompoundButton r : buttons) {
      r.setOnLongClickListener(l);
    }
  }

  @Override
  public void cancelLongPress() {
    super.cancelLongPress();
    for (CompoundButton button : this.buttons) {
      button.cancelLongPress();
    }
  }

}
