/*
 * 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.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Build;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.TimePicker;

import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.model.data.TimeData;
import org.javarosa.form.api.FormEntryPrompt;
import org.joda.time.DateTime;
import org.odk.collect.android.R;
import org.odk.collect.android.utilities.DateFormatter;

import java.util.Date;

/**
 * Displays a TimePicker widget.
 *
 * @author Carl Hartung (carlhartung@gmail.com)
 */
public class TimeWidget extends QuestionWidget {

  private static final int TIME_UNSET = -1;
  private TextView timePickerField;
  private long time;

  public TimeWidget(Context context, final FormEntryPrompt prompt) {

    super(context, prompt);

    time = TIME_UNSET;
    timePickerField = (TextView) LayoutInflater.from(context).inflate(R.layout.date_picker_field, this, false);
    timePickerField.setId(QuestionWidget.newUniqueId());
    final boolean readOnly = prompt.isReadOnly();
    timePickerField.setEnabled(!readOnly);
    timePickerField.setFocusable(false);
    timePickerField.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.answer_text));
    if (readOnly) {
      timePickerField.setBackgroundDrawable(null);
    }
    timePickerField.setClickable(false);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
      timePickerField.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO);
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
      timePickerField.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS);
    }

    TableLayout.LayoutParams params = new TableLayout.LayoutParams();

    params.setMargins(getResources().getDimensionPixelSize(R.dimen.edittext_padding_start), 0, 0, 0);
    timePickerField.setPadding(timePickerField.getPaddingLeft(), -1, timePickerField.getPaddingRight(),
        timePickerField.getPaddingBottom());
    timePickerField.setLayoutParams(params);
    timePickerField.setSingleLine(true);

    timePickerField.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(final View v) {
        showTimePickerDialog();
      }
    });

    setGravity(Gravity.START);
    addView(timePickerField);

    // If there's an answer, use it.
    setAnswer();
  }

  private void showTimePickerDialog() {
    TimePickerDialog.OnTimeSetListener listener = new TimePickerDialog.OnTimeSetListener() {
      @Override
      public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

        DateTime ldt = (new DateTime()).withTime(hourOfDay, minute, 0, 0);
        TimeData timeData = new TimeData(ldt.toDate());
        time = ((Date) timeData.getValue()).getTime();

        formatTime(time);
      }
    };

    boolean is24Hour = DateFormatter.is24Hour(getContext());

    DateTime ldt;

    if (time != TIME_UNSET) {
      ldt = new DateTime(time);
    } else {
      ldt = new DateTime((new Date()).getTime());
    }

    TimePickerDialog mTimePicker = new TimePickerDialog(getContext(), listener, ldt.getHourOfDay(), ldt
        .getMinuteOfHour(), is24Hour);

    mTimePicker.setButton(DialogInterface.BUTTON_NEUTRAL, getContext().getString(R.string.date_picker_clear),
        new DialogInterface.OnClickListener() {
          @Override
          public void onClick(final DialogInterface dialog, final int which) {
            if (which == DialogInterface.BUTTON_NEUTRAL) {
              timePickerField.setText("");
              time = TIME_UNSET;
            }
          }
        });

    mTimePicker.show();
  }

  private void setAnswer() {
    if (mPrompt.getAnswerValue() != null) {
      DateTime ldt = new DateTime(((Date) mPrompt.getAnswerValue().getValue()).getTime());
      time = ldt.toDate().getTime();
      formatTime(time);
    } else {
      // create date widget
      clearAnswer();
    }
  }

  private void formatTime(final long time) {
    timePickerField.setText(DateFormatter.formatTimePickerOutput(getContext(), time));
  }

  /**
   * Resets time to today.
   */
  @Override
  public void clearAnswer() {
    time = TIME_UNSET;
    timePickerField.setText("");
  }


  @Override
  public IAnswerData getAnswer() {
    clearFocus();

    if (time == TIME_UNSET) {
      return null;
    } else {
      return new TimeData(new Date(time));
    }
  }


  @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);
  }


  @Override
  public void setOnLongClickListener(OnLongClickListener l) {
    timePickerField.setOnLongClickListener(l);
  }


  @Override
  public void cancelLongPress() {
    super.cancelLongPress();
    timePickerField.cancelLongPress();
  }

}
