///|
pub(all) enum Calendar {
  Standard
  ProlepticGregorian
  Julian
  NoLeap
  AllLeap
  Days360
} derive(Eq)

///|
pub extend Calendar with Eq::{equal, not_equal}

///|
pub(all) struct CivilTime {
  year : Int32
  month : Int32
  day : Int32
  hour : Int32
  minute : Int32
  second : Int32
  microsecond : Int32
} derive(Eq)

///|
pub extend CivilTime with Eq::{equal, not_equal}

///|
pub struct TimeUnits {
  calendar : Calendar
  source : String
  microseconds_per_unit : Int64
  origin_microseconds : Int64
}

///|
pub fn calendar_from_name(name : String) -> Calendar raise CdfError {
  match name {
    "standard" | "gregorian" => Standard
    "proleptic_gregorian" => ProlepticGregorian
    "julian" => Julian
    "noleap" | "365_day" => NoLeap
    "all_leap" | "366_day" => AllLeap
    "360_day" => Days360
    _ => raise Unsupported("unsupported CF calendar")
  }
}

///|
fn is_leap(year : Int32, calendar : Calendar) -> Bool {
  match calendar {
    AllLeap => true
    NoLeap | Days360 => false
    Julian => year % 4 == 0
    Standard | ProlepticGregorian =>
      year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)
  }
}

///|
fn month_length(year : Int32, month : Int32, calendar : Calendar) -> Int32 {
  if calendar == Days360 {
    30
  } else if month == 2 {
    if is_leap(year, calendar) {
      29
    } else {
      28
    }
  } else if month == 4 || month == 6 || month == 9 || month == 11 {
    30
  } else {
    31
  }
}

///|
fn year_start(year : Int32, calendar : Calendar) -> Int64 {
  let previous = (year - 1).to_int64()
  fn floor_div(value : Int64, divisor : Int64) -> Int64 {
    if value < 0L {
      (value - divisor + 1L) / divisor
    } else {
      value / divisor
    }
  }
  match calendar {
    Days360 => previous * 360L
    NoLeap => previous * 365L
    AllLeap => previous * 366L
    Julian => previous * 365L + previous / 4L
    Standard | ProlepticGregorian =>
      previous * 365L +
      floor_div(previous, 4L) -
      floor_div(previous, 100L) +
      floor_div(previous, 400L)
  }
}

///|
fn date_ordinal(time : CivilTime, calendar : Calendar) -> Int64 raise CdfError {
  let minimum_year = if calendar == Standard || calendar == Julian {
    1
  } else {
    0
  }
  if time.year < minimum_year ||
    time.year > 9999 ||
    time.month < 1 ||
    time.month > 12 ||
    time.hour < 0 ||
    time.hour > 23 ||
    time.minute < 0 ||
    time.minute > 59 ||
    time.second < 0 ||
    time.second > 59 ||
    time.microsecond < 0 ||
    time.microsecond > 999999 {
    raise Invalid("time fields are outside supported civil ranges")
  }
  let before_cutover = time.year < 1582 ||
    (
      time.year == 1582 &&
      (time.month < 10 || (time.month == 10 && time.day < 15))
    )
  if calendar == Standard &&
    time.year == 1582 &&
    time.month == 10 &&
    time.day >= 5 &&
    time.day <= 14 {
    raise Invalid("date falls in the standard calendar Gregorian cutover gap")
  }
  let effective = if calendar == Standard && before_cutover {
    Julian
  } else {
    calendar
  }
  if time.day < 1 || time.day > month_length(time.year, time.month, effective) {
    raise Invalid("day does not exist in the selected calendar")
  }
  let mut result = year_start(time.year, effective)
  for month in 1.. Int64 raise CdfError {
  date_ordinal(time, calendar) * 86400000000L +
  (
    time.hour.to_int64() * 3600L +
    time.minute.to_int64() * 60L +
    time.second.to_int64()
  ) *
  1000000L +
  time.microsecond.to_int64()
}

///|
fn decimal_part(
  text : Array[Char],
  start : Int32,
  length : Int32,
) -> Int32 raise CdfError {
  if start < 0 || length < 1 || start > text.length() - length {
    raise Invalid("truncated CF time origin")
  }
  let mut value = 0
  for index in start..<(start + length) {
    let c = text[index]
    if c < '0' || c > '9' {
      raise Invalid("time origin requires decimal digits")
    }
    value = value * 10 + c.to_int() - 48
  }
  value
}

///|
fn origin_time(text : String) -> (CivilTime, Int32) raise CdfError {
  let chars = text.trim().to_owned().to_array()
  fn component(
    start : Int32,
    maximum_digits : Int32,
  ) -> (Int32, Int32) raise CdfError {
    let mut end = start
    while end < chars.length() && chars[end] >= '0' && chars[end] <= '9' {
      end += 1
    }
    if end == start || end - start > maximum_digits {
      raise Invalid("invalid numeric time component")
    }
    (decimal_part(chars, start, end - start), end)
  }
  let (year, after_year) = component(0, 4)
  if after_year >= chars.length() || chars[after_year] != '-' {
    raise Invalid("time origin requires year-month-day")
  }
  let (month, after_month) = component(after_year + 1, 2)
  if after_month >= chars.length() || chars[after_month] != '-' {
    raise Invalid("time origin requires year-month-day")
  }
  let (day, after_day) = component(after_month + 1, 2)
  let mut position = after_day
  let mut hour = 0
  let mut minute = 0
  let mut second = 0
  let mut microsecond = 0
  if position < chars.length() &&
    (chars[position] == 'T' || chars[position] == ' ') {
    position += 1
    while position < chars.length() && chars[position] == ' ' {
      position += 1
    }
    if position < chars.length() &&
      chars[position] >= '0' &&
      chars[position] <= '9' {
      let (parsed_hour, end) = component(position, 2)
      hour = parsed_hour
      position = end
      if position >= chars.length() || chars[position] != ':' {
        raise Invalid("clock requires HH:MM")
      }
      position += 1
      let (parsed_minute, end) = component(position, 2)
      minute = parsed_minute
      position = end
      if position < chars.length() && chars[position] == ':' {
        let (parsed_second, end) = component(position + 1, 2)
        second = parsed_second
        position = end
      }
      if position < chars.length() && chars[position] == '.' {
        position += 1
        let first = position
        while position < chars.length() &&
              chars[position] >= '0' &&
              chars[position] <= '9' {
          position += 1
        }
        let digits = position - first
        if digits < 1 || digits > 6 {
          raise Invalid("fractional seconds require one to six digits")
        }
        microsecond = decimal_part(chars, first, digits)
        for _ in digits..<6 {
          microsecond *= 10
        }
      }
    }
  }
  while position < chars.length() && chars[position] == ' ' {
    position += 1
  }
  let mut timezone_seconds = 0
  if position < chars.length() {
    if chars[position] == 'Z' {
      position += 1
    } else if chars[position] == '+' || chars[position] == '-' {
      let sign = if chars[position] == '+' { 1 } else { -1 }
      let zone_hour = decimal_part(chars, position + 1, 2)
      position += 3
      if position < chars.length() && chars[position] == ':' {
        position += 1
      }
      let zone_minute = decimal_part(chars, position, 2)
      position += 2
      if zone_hour > 23 || zone_minute > 59 {
        raise Invalid("invalid UTC offset")
      }
      timezone_seconds = sign * (zone_hour * 3600 + zone_minute * 60)
    } else {
      raise Invalid("unexpected trailing characters in CF time origin")
    }
  }
  if position != chars.length() {
    raise Invalid("unexpected trailing characters in CF time origin")
  }
  ({ year, month, day, hour, minute, second, microsecond, }, timezone_seconds)
}

///|
pub fn parse_time_units(
  text : String,
  calendar~ : Calendar = Standard,
) -> TimeUnits raise CdfError {
  let parts = text.split(" since ").to_array()
  if parts.length() != 2 {
    raise Invalid("CF relative time requires ' since '")
  }
  let unit = parts[0].trim().to_owned()
  let factor = match unit {
    "microseconds" | "microsecond" | "us" => 1L
    "milliseconds" | "millisecond" | "ms" => 1000L
    "seconds" | "second" | "s" => 1000000L
    "minutes" | "minute" | "min" => 60000000L
    "hours" | "hour" | "h" => 3600000000L
    "days" | "day" | "d" => 86400000000L
    "months" if calendar == Days360 => 2592000000000L
    "common_years" if calendar == NoLeap => 31536000000000L
    _ => raise Unsupported("unsupported unit for the selected CF calendar")
  }
  let (origin, timezone) = origin_time(parts[1].to_owned())
  let offset = civil_microseconds(origin, calendar) -
    timezone.to_int64() * 1000000L
  {
    calendar,
    source: text,
    microseconds_per_unit: factor,
    origin_microseconds: offset,
  }
}

///|
fn ordinal_civil(
  ordinal : Int64,
  remainder : Int64,
  calendar : Calendar,
) -> CivilTime raise CdfError {
  // Gregorian 1582-10-15 is day 577735 when 0001-01-01 is zero.
  let earlier = calendar == Standard && ordinal < 577735L
  let effective = if earlier { Julian } else { calendar }
  let day = if earlier { ordinal + 2L } else { ordinal }
  let minimum_year = if effective == Julian || effective == Standard {
    1
  } else {
    0
  }
  if day < year_start(minimum_year, effective) ||
    day >= year_start(10000, effective) {
    raise Unsupported(
      "time is outside the calendar's supported years 0/1 through 9999",
    )
  }
  let mut low = minimum_year
  let mut high = 10000
  while low + 1 < high {
    let middle = (low + high) / 2
    if year_start(middle, effective) <= day {
      low = middle
    } else {
      high = middle
    }
  }
  let mut day_in_year = day - year_start(low, effective)
  let mut month = 1
  while day_in_year >= month_length(low, month, effective).to_int64() {
    day_in_year -= month_length(low, month, effective).to_int64()
    month += 1
  }
  {
    year: low,
    month,
    day: day_in_year.to_int() + 1,
    hour: (remainder / 3600000000L).to_int(),
    minute: (remainder / 60000000L % 60L).to_int(),
    second: (remainder / 1000000L % 60L).to_int(),
    microsecond: (remainder % 1000000L).to_int(),
  }
}

///|
pub fn decode_time(
  value : Double,
  units : TimeUnits,
) -> CivilTime raise CdfError {
  let displacement = value * units.microseconds_per_unit.to_double()
  if displacement.is_nan() ||
    displacement.is_inf() ||
    displacement.abs() > 640000000000000000.0 {
    raise Unsupported("relative time exceeds supported civil range")
  }
  let total = units.origin_microseconds + @math.round(displacement).to_int64()
  let mut day = total / 86400000000L
  let mut remainder = total % 86400000000L
  if remainder < 0L {
    day -= 1L
    remainder += 86400000000L
  }
  ordinal_civil(day, remainder, units.calendar)
}

///|
pub fn encode_time(
  time : CivilTime,
  units : TimeUnits,
) -> Double raise CdfError {
  (civil_microseconds(time, units.calendar) - units.origin_microseconds).to_double() /
  units.microseconds_per_unit.to_double()
}

///|
fn padded_decimal(value : Int32, width : Int32) -> String {
  let text = value.to_string()
  let mut output = ""
  for _ in text.length().. String {
  padded_decimal(self.year, 4) +
  "-" +
  padded_decimal(self.month, 2) +
  "-" +
  padded_decimal(self.day, 2) +
  "T" +
  padded_decimal(self.hour, 2) +
  ":" +
  padded_decimal(self.minute, 2) +
  ":" +
  padded_decimal(self.second, 2) +
  "." +
  padded_decimal(self.microsecond, 6)
}

///|
pub fn Dataset::times(
  self : Dataset,
  name : String,
) -> Array[CivilTime?] raise CdfError {
  let variable = self.find(name)
  self.time_section(
    name,
    Array::make(variable.shape.length(), 0L),
    variable.shape,
  )
}

///|
pub fn Dataset::time_section(
  self : Dataset,
  name : String,
  start : Array[Int64],
  count : Array[Int64],
  stride~ : Array[Int64] = [],
) -> Array[CivilTime?] raise CdfError {
  let variable = self.find(name)
  let units_attribute = match find_attribute(variable.attributes, "units") {
    Some(attribute) => attribute
    None => raise Invalid("time variable requires a units attribute")
  }
  let calendar = match find_attribute(variable.attributes, "calendar") {
    Some(attribute) => calendar_from_name(attribute_text(attribute))
    None => Standard
  }
  let units = parse_time_units(attribute_text(units_attribute), calendar~)
  let physical = self.physical_section(name, start, count, stride~)
  physical.values.map(value => {
    match value {
      None => None
      Some(number) => Some(decode_time(number, units))
    }
  })
}