/*
 * Copyright (c) 2015 Diona Ltd.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of Diona
 * ("Confidential Information"). You shall not disclose such Confidential Information
 * and shall use it only in accordance with the terms of the license agreement you
 * entered into with Diona.
 */
package org.odk.collect.android.utilities;

import android.content.Context;
import android.text.format.DateUtils;

import java.util.Date;

/**
 * Formats dates and times.
 */
public final class DateFormatter {

  /**
   * Constant for 24 hour indicator.
   */
  private static final String HOUR_24 = "24";
  private static final int timeFlags = DateUtils.FORMAT_SHOW_TIME;
  private static final int dateFlags =
      DateUtils.FORMAT_ABBREV_ALL | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR;

  /**
   * Format the text selected from a date picker for display in a TextView to the user.
   *
   * @param context
   *     an active Context.
   * @param date
   *     the date to format.
   *
   * @return the formatted date.
   */
  public static String formatDatePickerOutput(final Context context, final Date date) {
    if (date == null) {
      return "";
    }
    return formatDatePickerOutput(context, date.getTime());
  }

  /**
   * Format the text selected from a date picker for display in a TextView to the user.
   *
   * @param context
   *     an active Context.
   * @param date
   *     the date in milliseconds to format.
   *
   * @return the formatted date.
   */
  public static String formatDatePickerOutput(final Context context, final long date) {
    return DateUtils.formatDateTime(context, date, dateFlags);
  }

  /**
   * Format the time selected from a time picker for display to the user.
   *
   * @param context
   *     the current Context.
   * @param time
   *     the time to format in milliseconds.
   *
   * @return the formatted text.
   */
  public static String formatTimePickerOutput(final Context context, final long time) {
    return DateUtils.formatDateTime(context, time, timeFlags);
  }

  public static String formatDateTime(final Context context, final long dateTime) {
    return DateUtils.formatDateTime(context, dateTime, dateFlags | timeFlags);
  }

  /**
   * @param context
   *     the current Context.
   *
   * @return {@code true} if the system is set to display 24-hour times, {@code false} if the system is set to display
   * 12-hour times.
   */
  public static boolean is24Hour(final Context context) {
    String clockType =
        android.provider.Settings.System.getString(context.getContentResolver(),
            android.provider.Settings.System.TIME_12_24);
    return (clockType == null || clockType.equalsIgnoreCase(HOUR_24));
  }
}
