/*
 * Copyright (C) 2020  Max Regan
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

#include "Bsp/Drivers/GpioDriver.h"

#include "Application/ButtonManager.h"

#include "TestBoard.h"

#include "printf.h"
#include "test.h"

using namespace BSP;

using Button = ButtonManager::Button;
using ButtonState = ButtonManager::ButtonState;

static GpioPin g_btn_down(g_gpioa, 0);
static GpioPin g_btn_mid(g_gpioa, 1);
static GpioPin g_btn_up(g_gpioa, 2);

static ButtonManager g_btn_mgr(g_sched,
                               g_btn_down,
                               g_btn_mid,
                               g_btn_up,
                               Time::millis(50));

class IdleTask : public BSP::Schedule::Task {
public:
    IdleTask()
    {}

    BSP::Schedule::NextTime execute() override {
        return BSP::Schedule::NextTime::asap();
    }
};

static IdleTask g_idle;

[[noreturn]] void main() {

    board_init();

    g_test_uart.tx_blocking(test_start_text);
    
    g_btn_down.configure_input(GpioDriver::input_pull_t::PULL_UP);
    g_btn_mid.configure_input(GpioDriver::input_pull_t::PULL_UP);
    g_btn_up.configure_input(GpioDriver::input_pull_t::PULL_UP);

    g_btn_mgr.init();

    ButtonManager::ChangeCallback callback =
        [&](ButtonState state) {
            g_test_uart.tx_blocking("up:");
            if (state == ButtonState::PRESSED) {
                g_test_uart.tx_blocking("pressed\r\n");
            } else {
                g_test_uart.tx_blocking("released\r\n");
            }
        };

    g_btn_mgr.set_callback(Button::UP, callback);

    Schedule::NextTime asap = Schedule::NextTime::asap();
    g_sched.add_task(g_test_uart, asap);
    g_sched.add_task(g_btn_mgr, asap);
    g_sched.add_task(g_idle, asap);

    g_test_uart.tx_blocking("Waiting for button press...\r\n");
    g_sched.run();

    TEST_SPIN();
}
