/*
 * 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 "printf.h"

#include "TestBoard.h"

#include "test.h"

using BSP::Time;
using BSP::ReturnCode;
using BSP::SystemTimer;
using BSP::time_t;
using BSP::WallClockTime;
using BSP::RtcDriver;

static char buffer[128] = {0};

void run_case(unsigned int hours, unsigned int minutes, unsigned int seconds) {
    WallClockTime t0(hours, minutes, seconds);
    WallClockTime t1;
    RtcDriver::set_time(t0);
    RtcDriver::get_time(t1);

    snprintf(buffer, sizeof(buffer),
             "Testing with %d:%02d:%02d...",
             hours, minutes, seconds);
    g_test_uart.tx_blocking(buffer);

    if (t0.get_hours_24() != hours
        || t0.get_minutes() != minutes
        || t0.get_seconds() != seconds) {
        snprintf(buffer, sizeof(buffer),
                 "Software representation changed. Got:%d:%02d:%02d\r\n",
                 t0.get_hours_24(), t0.get_minutes(), t0.get_seconds());

        g_test_uart.tx_blocking(buffer);
        g_test_uart.tx_blocking(test_fail_text);
        TEST_SPIN();
    }

    if (t0 != t1) {
        snprintf(buffer, sizeof(buffer),
                 "Value from RTC does not match. Got %d:%02d:%02d\r\n",
                 t1.get_hours_24(), t1.get_minutes(), t1.get_seconds());
        g_test_uart.tx_blocking(buffer);
        g_test_uart.tx_blocking(test_fail_text);
        TEST_SPIN();
    }

    g_test_uart.tx_blocking("OK\r\n");
}

[[noreturn]] void main() {

    board_init();

    g_test_uart.tx_blocking(test_start_text);

    run_case(10, 0, 0);
    run_case(0, 0, 0);
    run_case(10, 59, 59);
    run_case(12, 0, 0);
    run_case(23, 59, 59);

    g_test_uart.tx_blocking(test_pass_text);

    TEST_SPIN();
}
