///|
/// UTC start time with a one-based ordinal day and a nanosecond fraction.
#derive(Eq)
pub(all) struct SampleTime {
  year : Int32
  day : Int32
  hour : Int32
  minute : Int32
  second : Int32
  nanosecond : Int32
}

///|
pub(all) suberror WaveformError {
  InvalidWaveform(String)
}

///|
pub impl Show for WaveformError with fn output(self, logger) {
  let InvalidWaveform(message) = self
  logger.write_string(message)
}

///|
fn before_year(year : Int32) -> Int32 {
  let y = year - 1
  y * 365 + y / 4 - y / 100 + y / 400
}

///|
fn elapsed(rate : Double, offset : Int64) -> (Int64, Int32) raise WaveformError {
  guard offset >= 0L && rate.is_finite() && rate != 0.0 else {
    raise InvalidWaveform(
      "sample offset must be nonnegative and sample rate finite and nonzero",
    )
  }
  if rate >= 1.0 && rate <= 1000000000.0 && rate == rate.trunc() {
    let hz = rate.to_int64()
    return (offset / hz, ((offset % hz * 1000000000L + hz / 2L) / hz).to_int())
  }
  // The binary64 magnitude is significand * 2^power. Subnormals have no
  // implicit leading bit and share the exponent of the smallest normal.
  let bits = rate.abs().reinterpret_as_uint64()
  let exponent = (bits >> 52).to_int()
  let fraction = bits & 0x000fffffffffffffUL
  let significand = if exponent == 0 {
    fraction
  } else {
    fraction | (1UL << 52)
  }
  let power = exponent.max(1) - 1075
  let rate_numerator = @bigint.BigInt::from_uint64(significand) << power.max(0)
  let rate_denominator = 1N << (-power).max(0)
  let ticks = @bigint.BigInt::from_int64(offset) * 1000000000N
  let (numerator, denominator) = if rate > 0.0 {
    (ticks * rate_denominator, rate_numerator)
  } else {
    (ticks * rate_numerator, rate_denominator)
  }
  let nanoseconds = (numerator + (denominator >> 1)) / denominator
  let seconds = nanoseconds / 1000000000N
  guard seconds <= 316000000000N else {
    raise InvalidWaveform("sample timestamp exceeds the calendar range")
  }
  (seconds.to_int64(), (nanoseconds % 1000000000N).to_int())
}

///|
/// Advance from an original record start by an absolute sample index. Positive
/// rates are hertz, negative rates are seconds per sample. The result is rounded
/// to the nearest nanosecond. An explicitly encoded leap second is preserved.
pub fn time_at(
  start : SampleTime,
  rate : Double,
  offset : Int64,
) -> SampleTime raise WaveformError {
  guard start.year >= 1 &&
    start.year <= 9999 &&
    start.day >= 1 &&
    start.day <= before_year(start.year + 1) - before_year(start.year) &&
    start.hour >= 0 &&
    start.hour < 24 &&
    start.minute >= 0 &&
    start.minute < 60 &&
    start.second >= 0 &&
    start.second <= 60 &&
    start.nanosecond >= 0 &&
    start.nanosecond < 1000000000 else {
    raise InvalidWaveform(
      "invalid UTC sample time (supported years 1 through 9999)",
    )
  }
  let (whole, fraction) = elapsed(rate, offset)
  guard whole <= 316000000000L else {
    raise InvalidWaveform("sample timestamp exceeds year 9999")
  }
  let ns = start.nanosecond + fraction
  if start.second == 60 && whole == 0L && ns < 1000000000 {
    return { ..start, nanosecond: ns, }
  }
  let secs = (start.hour * 3600 + start.minute * 60 + start.second.min(59)).to_int64() +
    whole +
    (ns / 1000000000).to_int64()
  let ordinal = before_year(start.year) +
    start.day -
    1 +
    (secs / 86400L).to_int()
  guard ordinal < before_year(10000) else {
    raise InvalidWaveform("sample timestamp exceeds year 9999")
  }
  let mut low = start.year
  let mut high = 10000
  while low + 1 < high {
    let mid = (low + high) / 2
    if before_year(mid) <= ordinal {
      low = mid
    } else {
      high = mid
    }
  }
  let tod = (secs % 86400L).to_int()
  {
    year: low,
    day: ordinal - before_year(low) + 1,
    hour: tod / 3600,
    minute: tod / 60 % 60,
    second: tod % 60,
    nanosecond: ns % 1000000000,
  }
}