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

///|
/// Read the record start without changing its civil-time fields.
pub fn SampleTime::from_header(header : @mseed.Header) -> SampleTime {
  {
    year: header.year,
    day: header.day,
    hour: header.hour,
    minute: header.minute,
    second: header.second,
    nanosecond: header.nanosecond,
  }
}

///|
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
}

///|
priv enum SampleDuration {
  // Common integer-hertz clocks fit in seconds with a nanosecond fraction.
  Seconds(Int64, Int32)
  Nanoseconds(@bigint.BigInt)
}

///|
fn sample_duration(
  rate : Double,
  offset : Int64,
) -> SampleDuration 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 Seconds(
      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)
  }
  Nanoseconds((numerator + (denominator >> 1)) / denominator)
}

///|
/// Exact physical duration of a nonnegative number of sample intervals,
/// rounded to the nearest nanosecond. Positive rates are hertz and negative
/// rates are seconds per sample. The duration is independent of civil dates.
pub fn sample_duration_ns(
  rate : Double,
  offset : Int64,
) -> @bigint.BigInt raise WaveformError {
  match sample_duration(rate, offset) {
    Seconds(s, ns) =>
      @bigint.BigInt::from_int64(s) * 1000000000N + @bigint.BigInt::from_int(ns)
    Nanoseconds(ns) => ns
  }
}

///|
fn elapsed(rate : Double, offset : Int64) -> (Int64, Int32) raise WaveformError {
  let nanoseconds = match sample_duration(rate, offset) {
    Seconds(s, ns) => return (s, ns)
    Nanoseconds(ns) => ns
  }
  let seconds = nanoseconds / 1000000000N
  guard seconds <= 316000000000N else {
    raise InvalidWaveform("sample timestamp exceeds the calendar range")
  }
  (seconds.to_int64(), (nanoseconds % 1000000000N).to_int())
}

///|
/// Check the Gregorian ordinal date, UTC clock fields and nanosecond fraction.
pub fn SampleTime::validate(self : SampleTime) -> Unit raise WaveformError {
  guard self.year >= 1 &&
    self.year <= 9999 &&
    self.day >= 1 &&
    self.day <= before_year(self.year + 1) - before_year(self.year) &&
    self.hour >= 0 &&
    self.hour < 24 &&
    self.minute >= 0 &&
    self.minute < 60 &&
    self.second >= 0 &&
    self.second <= 60 &&
    self.nanosecond >= 0 &&
    self.nanosecond < 1000000000 else {
    raise InvalidWaveform(
      "invalid UTC sample time (supported years 1 through 9999)",
    )
  }
}

///|
/// 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 {
  start.validate()
  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,
  }
}