/*
 * Copyright (C) 2019  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 <algorithm>
#include <cmath>

#include "Application/Screens/AnalogTimeScreen.h"
#include "Application/SystemFonts.h"
#include "Bsp/Drivers/RtcDriver.h"
#include "Bsp/SystemTime.h"
#include "Bsp/Drivers/LowPower.h"

using BSP::ReturnCode;
using BSP::Time;
using BSP::Schedule::NextTime;
using Color = BSP::DisplayDriver::Color;

// TODO: remove all calls to std::cos and std::sin?

AnalogTimeScreen::AnalogTimeScreen(BSP::DisplayDriver &driver,
                                     ScreenManager &manager,
                                     Screen &menu_screen)
    : m_driver(driver)
    , m_last_time()
    , m_manager(manager)
    , m_menu_screen(menu_screen)
    , m_display_seconds(true)
{}

ReturnCode AnalogTimeScreen::init()
{
    return ReturnCode::OK;
}

void AnalogTimeScreen::draw_ticks() {

    // After profiling, using lookup tables is 6-10% faster than using std::sin & std::cos.
    static constexpr float sin_tbl[8] = {
        0.0,
        0.10452539173303049,
        0.20790564888802265,
        0.30900818248165035,
        0.4067253572759511,
        0.4999866265466325,
        0.5877702605258084,
        0.6691145400274635,
    };

    static constexpr float cos_tbl[8] = {
        1.0,
        0.9945222181947755,
        0.9781488849661131,
        0.9510593794077146,
        0.9135504823209005,
        0.8660331248136633,
        0.8090278863187741,
        0.7431592913526923,
    };

    const uint32_t y_center = m_driver.get_height() / 2;
    const uint32_t x_center = m_driver.get_width()  / 2;
    const uint32_t radius = std::min(m_driver.get_width(), m_driver.get_height()) / 2;

    // This only works for square screens, but saves a a bunch of float math and calls to trig functions

    for (int i = 0; i < 8; i++) {
        const uint32_t len = (i % 5 == 0) ? 10 : 5;
        const uint32_t width = (i % 5 == 0) ? 3 : 1;
        const uint32_t end1_offset = sin_tbl[i] * radius;
        const uint32_t end2_offset = cos_tbl[i] * radius;
        const uint32_t start1_offset = sin_tbl[i] * (radius - len);
        const uint32_t start2_offset = cos_tbl[i] * (radius - len);

        m_driver.draw_line(x_center + start1_offset, y_center + start2_offset,
                           x_center + end1_offset, y_center + end2_offset,
                           Color::BLACK, width);
        m_driver.draw_line(x_center - start1_offset, y_center + start2_offset,
                           x_center - end1_offset, y_center + end2_offset,
                           Color::BLACK, width);
        m_driver.draw_line(x_center + start1_offset, y_center - start2_offset,
                           x_center + end1_offset, y_center - end2_offset,
                           Color::BLACK, width);
        m_driver.draw_line(x_center - start1_offset, y_center - start2_offset,
                           x_center - end1_offset, y_center - end2_offset,
                           Color::BLACK, width);

        m_driver.draw_line(x_center + start2_offset, y_center + start1_offset,
                           x_center + end2_offset, y_center + end1_offset,
                           Color::BLACK, width);
        m_driver.draw_line(x_center - start2_offset, y_center + start1_offset,
                           x_center - end2_offset, y_center + end1_offset,
                           Color::BLACK, width);
        m_driver.draw_line(x_center + start2_offset, y_center - start1_offset,
                           x_center + end2_offset, y_center - end1_offset,
                           Color::BLACK, width);
        m_driver.draw_line(x_center - start2_offset, y_center - start1_offset,
                           x_center - end2_offset, y_center - end1_offset,
                           Color::BLACK, width);
    }
}

void AnalogTimeScreen::draw_hand(uint32_t ticks, uint32_t len, int32_t width, Color color) {

    const uint32_t y_center = m_driver.get_height() / 2;
    const uint32_t x_center = m_driver.get_width()  / 2;

    uint32_t x_end = x_center + std::sin(ticks * TURNS_PER_TICK) * len;
    uint32_t y_end = y_center - std::cos(ticks * TURNS_PER_TICK) * len;

    m_driver.draw_line(x_center, y_center, x_end, y_end, color, width);
}

void AnalogTimeScreen::display_time()
{
    BSP::WallClockTime time;
    BSP::RtcDriver::get_time(time);

    m_driver.clear(Color::WHITE);

    draw_ticks();

    const uint32_t seconds_len = std::min(m_driver.get_width(), m_driver.get_height()) * 9 / 20;
    const uint32_t minutes_len = std::min(m_driver.get_width(), m_driver.get_height()) * 17 / 40;
    const uint32_t hours_len = std::min(m_driver.get_width(), m_driver.get_height()) * 6 / 20;

    draw_hand(time.get_hours_12() * 5, hours_len, 3, Color::BLACK);
    draw_hand(time.get_minutes(), minutes_len, 3, Color::BLACK);

    if (m_display_seconds) {
        draw_hand(time.get_seconds(), seconds_len, 2, Color::RED);
    }

    m_last_time = time;
    m_driver.refresh();
}

NextTime AnalogTimeScreen::execute()
{
    display_time();

    BSP::time_t now;
    BSP::SystemTimer::get_time(now);
    if (m_display_seconds) {
        return NextTime::in(Time::seconds(1));
    } else {

        BSP::WallClockTime wall_time;
        BSP::RtcDriver::get_time(wall_time);
        return NextTime::in(Time::seconds(61 - wall_time.get_seconds()));
    }
}


void AnalogTimeScreen::enable() {
    m_last_time = {};
    display_time();
}

void AnalogTimeScreen::disable() {
}

void AnalogTimeScreen::notify_up_button() {
    /* TODO: This should open a menu first */
    m_manager.push_screen(m_menu_screen);
}

void AnalogTimeScreen::notify_middle_button() {

}

void AnalogTimeScreen::notify_down_button() {

}
