#include "RunStats.h"

namespace field_qa {

void RunStats::begin(uint32_t nowMs) {
  m_bootMs = nowMs;
  m_noFixStartMs = nowMs;
  m_longestNoFixMs = 0;
  m_ttffMs = 0;
  m_started = true;
  m_haveFirstFix = false;
}

void RunStats::updateFromSample(const GnssSample& sample, uint32_t nowMs) {
  if (!m_started) {
    begin(nowMs);
  }

  if (sample.validFix) {
    if (!m_haveFirstFix) {
      m_ttffMs = nowMs - m_bootMs;
      m_haveFirstFix = true;
    }
    if (m_noFixStartMs != 0) {
      uint32_t noFixMs = nowMs - m_noFixStartMs;
      if (noFixMs > m_longestNoFixMs) {
        m_longestNoFixMs = noFixMs;
      }
      m_noFixStartMs = 0;
    }
  } else if (m_noFixStartMs == 0) {
    m_noFixStartMs = nowMs;
  }
}

uint32_t RunStats::elapsedMs(uint32_t nowMs) const {
  return m_started ? (nowMs - m_bootMs) : 0;
}

uint32_t RunStats::longestNoFixMs() const {
  return m_longestNoFixMs;
}

uint32_t RunStats::ttffMs() const {
  return m_ttffMs;
}

bool RunStats::hasFirstFix() const {
  return m_haveFirstFix;
}

}  // namespace field_qa

