// Copyright (C) 2026 Hector van der Aa <hector@h3cx.dev>
// Copyright (C) 2026 Pierre Barbier <pierrebarbier741@gmail.com>
// Copyright (C) 2026 Association Exergie <association.exergie@gmail.com>
// SPDX-License-Identifier: GPL-3.0-or-later

#include "cmsis_os2.h"
#include "global_state.h"
#include "macros.h"
#include "main.h"
#include "ring_buffer.h"
#include "tasks.h"

void camHandler(void *argument) {
  for (;;) {
    osThreadFlagsWait(0x01, osFlagsWaitAny, osWaitForever);

    DEBUG_LOG("Cam pulse detected at: %lu\n\r",
              ringBufferRead(&state_g.cam_RB, 0));

    // FILTERS
    // if (CAM_TRIGD) {
    //     ringBufferRevert(&state_g.cam_RB,1);
    //     return;
    // }
    state_g.cam_state = CAM_TRIGD;
    state_g.cam_miss_ctr = 0;
    switch (state_g.sync_state) {
    case SYNC_NOT_OK: {
      state_g.sync_state = SYNC_PENDING;
      DEBUG_LOG("Sync state updated to pending\n\r");
      break;
    }
    case SYNC_PENDING: {
      if (state_g.crank_state == CYCLE_COMPRESSION) {
        state_g.sync_state = SYNC_OK;
        DEBUG_LOG("Sync state updated to OK\n\r");
      }
      break;
    }
    default:
      break;
    }
  }
}
