#pragma once
#include <stdint.h>
#include <math.h>

class Orientation180 {
 public:
  bool flipped = false;

  bool update(uint32_t now, float screenUpG, float lateralG, float normalG) {
    const float norm2 = screenUpG * screenUpG + lateralG * lateralG + normalG * normalG;
    const bool stable = isfinite(norm2) && norm2 >= .64f && norm2 <= 1.44f &&
                        fabsf(screenUpG) >= .60f && fabsf(screenUpG) >= fabsf(lateralG) + .15f;

    if (!stable || (sampled && uint32_t(now - lastSample) > 120)) {

      pending = false;

    }

    sampled = true;
    lastSample = now;

    if (!stable) {

      return false;

    }

    const bool target = screenUpG < 0;

    if (target == flipped) {

      pending = false;
      return false;

    }

    if (!pending || target != candidate) {

      pending = true;
      candidate = target;
      since = now;
      return false;

    }

    if (uint32_t(now - since) < 600) {

      return false;

    }

    flipped = target;
    pending = false;
    return true;
  }

 private:
  bool pending = false, candidate = false, sampled = false;
  uint32_t since = 0, lastSample = 0;
};
