import moment from 'moment-timezone';
import * as RNLocalize from 'react-native-localize';

export const DATE_FORMAT = 'MMMM DD, YYYY';
export const DATE_FORMAT_12H = 'DD/MM/YYYY - h:mm A';
export const DATE_FORMAT_24H = 'DD/MM/YYYY - HH:mm';
export const DATE_FORMAT_ZULU_TIME = 'YYYY-MM-DD HH:mm:ss.SSS Z'; // 2020-06-03 15:34:02.1234 +0000 UTC
export const HOUR_FORMAT_12H = 'h:mm A';
export const HOUR_FORMAT_24H = 'HH:mm';

export type DATE_FORMATS =
  | typeof DATE_FORMAT
  | typeof DATE_FORMAT_12H
  | typeof DATE_FORMAT_24H
  | typeof DATE_FORMAT_ZULU_TIME;
export type HOURS_FORMATS = typeof HOUR_FORMAT_12H | typeof HOUR_FORMAT_24H;
export type DATETIME_FORMATS = DATE_FORMATS | HOURS_FORMATS;

/**
 * Convert timestamp to milliseconds.
 *
 * @param {number} timestamp Timestamp
 */
function parseTimestamp(timestamp: number) {
  if (timestamp >= 1e16 || timestamp <= -1e16) {
    // Assuming that timestamp is in nanoseconds (1 billionth of a second)
    return Math.floor(timestamp / 1000000);
  } else if (timestamp >= 1e14 || timestamp <= -1e14) {
    // Assuming that timestamp is in microseconds (1/1,000,000 second)
    return Math.floor(timestamp / 1000);
  } else if (timestamp >= 1e11 || timestamp <= -3e10) {
    // Assuming that timestamp is in milliseconds
    return timestamp;
  } else {
    // Assuming that timestamp is in seconds
    if (timestamp > 1e11 || timestamp < -1e10) {
      // Remove the last 3 digits if you are trying to convert milliseconds
    }
    return timestamp * 1000;
  }
}

export function formatDate(date: moment.Moment, format: DATE_FORMATS | HOURS_FORMATS) {
  return date.tz(RNLocalize.getTimeZone()).format(format);
}

export function parseDate(date: string, format: DATE_FORMATS) {
  return moment(date, format);
}

export function parseFromUnix(timestamp: number) {
  const millisecondsSinceUnix = parseTimestamp(timestamp);

  return moment(millisecondsSinceUnix);
}

export function formatTimestampHour(value: number, format: HOURS_FORMATS) {
  return formatDate(parseFromUnix(value), format);
}
