#include "main.h"

#include <stdio.h>
#include "sdkconfig.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_rom_gpio.h"
#include "esp_heap_caps.h"

#include "drivers/all.h"
#include "drivers/state_tracking.h"

#include "helper.h"

#include "steps/step0.h"
#include "steps/step1.h"
#include "steps/step2.h"
#include "steps/step3.h"
#include "steps/step4.h"
#include "steps/step5.h"
#include "steps/step6.h"

static const char *TAG = "main";
uint32_t initial_game_time = 90*60*1000 + 1000;
uint32_t skip_to_step = 0;
uint32_t current_step = 0;
extern uint32_t total_strikes;

extern "C" void app_main(void) {
    printf("app_main\n");

    init_drivers();

    // TODO: get wires out of the drivers
    // TODO: generify the strike system out of wires
    init_wires();
    vTaskDelay(pdMS_TO_TICKS(1000));

    clean_bomb();
    lcd_do_splash();
    step0();

    // set_recording_source(stdout, false);
    FILE* record_file = fopen(MOUNT_POINT "/record.txt", "w");
    if (record_file == nullptr) {
        ESP_LOGE("main", "failed to open record.txt");
    }
    set_recording_source(record_file, true);
    start_recording();

    set_game_time(initial_game_time);
    start_game_timer();
    total_strikes = 0;
    clean_bomb();
    current_step = 1;
    if (skip_to_step <= 1) step1();
    step_finish_times[current_step-1] = get_game_time();
    clean_bomb();
    current_step = 2;
    if (skip_to_step <= 2) step2();
    step_finish_times[current_step-1] = get_game_time();
    clean_bomb();
    current_step = 3;
    if (skip_to_step <= 3) step3();
    step_finish_times[current_step-1] = get_game_time();
    clean_bomb();
    current_step = 4;
    if (skip_to_step <= 4) step4();
    step_finish_times[current_step-1] = get_game_time();
    clean_bomb();
    current_step = 5;
    if (skip_to_step <= 5) step5();
    step_finish_times[current_step-1] = get_game_time();
    clean_bomb();
    current_step = 6;
    if (skip_to_step <= 6) step6();
    start_game_timer();
    step_finish_times[current_step-1] = get_game_time();
    clean_bomb();

    stop_game_timer();
    ESP_LOGI(TAG, "Bomb has been diffused. Counter-Terrorists win.");
    play_clip_wav(MOUNT_POINT "/diffuse.wav", true, false, 3, 0);

    display_game_results();
    stop_recording();

}
