/*
 * 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 "Bsp/LowPowerTaskScheduler.h"
#include "Bsp/Drivers/RtcDriver.h"
#include "Bsp/Drivers/DisplayDriver.h"
#include "Bsp/Drivers/SpiDriver.h"
#include "Bsp/Drivers/LptimPwm.h"

#include "Application/ButtonManager.h"

#include "Application/ScreenManager.h"
#include "Application/Screens/AnalogTimeScreen.h"
#include "Application/Screens/BigDigitalTimeScreen.h"
#include "Application/Screens/DebugScreen.h"
#include "Application/Screens/MenuScreen.h"
#include "Application/Screens/SetTimeScreen.h"
#include "Application/Screens/SetDateScreen.h"

#include "Bsp/macros.h"

// TODO: Don't include this here.
#include "stm32l0xx.h"

using BSP::Time;

static BSP::Schedule::LowPowerTaskScheduler<5> g_sched;
static BSP::SpiDriver g_spi(g_sched);
static BSP::DisplayDriver g_display(g_sched, g_spi);
static BSP::LptimPwm g_lptim_pwm(LPTIM1);
static BSP::ButtonManager g_btn_manager(g_sched, 2, 1, 0, Time::millis(1));

static ScreenManager g_screen_manager(g_sched, g_display, g_btn_manager);
static SetTimeScreen g_set_time_screen(g_display, g_screen_manager);
static SetTimeScreen g_set_date_screen(g_display, g_screen_manager);

static MenuScreen g_enable_debug(g_display,
                                 g_screen_manager,
                                 "SW Update",
                                 std::initializer_list<MenuScreenItem>({MenuScreenItem("Enable", []() { BSP::LowPower::enable_debug(); }),
                                                                        MenuScreenItem("Disable", []() { BSP::LowPower::disable_debug();
                                                                                                 })}));
// static DebugScreen g_debug_screen(g_display, g_screen_manager);

static MenuScreen g_settings_menu_screen(g_display,
                                         g_screen_manager,
                                         "Settings",
                                         std::initializer_list<MenuScreenItem>({MenuScreenItem("Set Time", g_set_time_screen),
                                                                                MenuScreenItem("Set Date", g_set_date_screen),
                                                                                MenuScreenItem("Set Face", g_set_date_screen),
                                                                                MenuScreenItem("SW Update", g_enable_debug)}));
static MenuScreen g_main_menu_screen(g_display,
                                     g_screen_manager,
                                     "Main Menu",
                                     std::initializer_list<MenuScreenItem>({MenuScreenItem("Apps", g_settings_menu_screen),
                                                                            MenuScreenItem("Settings", g_settings_menu_screen)}));

static AnalogTimeScreen g_display_time_screen(g_display, g_screen_manager, g_main_menu_screen);

extern "C" void __cxa_pure_virtual() { while(1) {} }

void SystemInit()
{
    /**
     * Use the MSI for the system clock, and disable all other clocks.
     */

    /*!< Set MSION bit. Set by hardware to force the MSI oscillator ON
     * when exiting from Stop or Standby mode, or in case of a failure
     * of the HSE oscillator used directly or indirectly as system
     * clock. This bit cannot be cleared if the MSI is used as system
     * clock. */
    SET(RCC->CR,
        RCC_CR_MSION);

    SET_TO(RCC->ICSCR,
           RCC_ICSCR_MSIRANGE,
           RCC_ICSCR_MSIRANGE_6);

    /*!< Set internal representation of clock frequency to 4MHz */
    // system_clk_freq = 4u << 22;

    /*!< Reset
     * SW[1:0] (use MSI oscillator as system clock),
     * HPRE[3:0] (do not divide AHB clock in prescaler) ,
     * PPRE1[2:0] (do not divide APB low-speed clock)
     * PPRE2[2:0] (do not divide APB high-speed clock),
     * MCOSEL[2:0] (disable MCO clock),
     * MCOPRE[2:0] (disable MCO prescaler) */
    CLR(RCC->CFGR,
          RCC_CFGR_SW | ~RCC_CFGR_HPRE | RCC_CFGR_PPRE1 | RCC_CFGR_PPRE2 |
          RCC_CFGR_MCOSEL | RCC_CFGR_MCOPRE);

    /*!< Reset
     * HSION (disable HSI),
     * HSIDIVEN (disable 18MHz HSI division)
     * HSEON (disable HSE clock)
     * CSSHSEON (disable HSE clock monitoring)
     * PLLON (disable PLL)
     */
    CLR(RCC->CR,
          RCC_CR_HSION | RCC_CR_HSIDIVEN | RCC_CR_HSEON |
          RCC_CR_CSSHSEON | RCC_CR_PLLON);

    /*!< Reset HSEBYP bit (disable HSE bypass) */
    CLR(RCC->CR,
          RCC_CR_HSEBYP)
       ;

    /* (1) Test if PLL is used as System clock */
    /* (2) Select HSI as system clock */
    /* (3) Wait for HSI switched */
    /* (4) Disable the PLL */
    /* (5) Wait until PLLRDY is cleared */
    /* (6) Set latency to 1 wait state */
    /* (7) Set the PLL multiplier to 24 and divider by 3 */
    /* (8) Enable the PLL */
    /* (9) Wait until PLLRDY is set */
    /* (10) Select PLL as system clock */
    /* (11) Wait until the PLL is switched on */

    // SET(RCC->CR, RCC_CR_HSION);
    // while((RCC->CR & RCC_CR_HSIRDY) != 0) {}

    // if ((RCC->CFGR & RCC_CFGR_SWS) == RCC_CFGR_SWS_PLL) /* (1) */
    // {
    //     RCC->CFGR = (RCC->CFGR & (uint32_t) (~RCC_CFGR_SW)) | RCC_CFGR_SW_HSI; /* (2) */
    //     while ((RCC->CFGR & RCC_CFGR_SWS) != RCC_CFGR_SWS_HSI) /* (3) */
    //     { /* For robust implementation, add here time-out management */ }
    // }

    // RCC->CR &= (uint32_t)(~RCC_CR_PLLON);/* (4) */
    // while((RCC->CR & RCC_CR_PLLRDY) != 0) /* (5) */
    // { /* For robust implementation, add here time-out management */ }

    // FLASH->ACR |= FLASH_ACR_LATENCY; /* (6) */
    // RCC->CFGR = RCC->CFGR & ((~(RCC_CFGR_PLLMUL| RCC_CFGR_PLLDIV )) | (RCC_CFGR_PLLMUL24 | RCC_CFGR_PLLDIV2)); /* (7) */
    // RCC->CR |= RCC_CR_PLLON; /* (8) */

    // while ((RCC->CR & RCC_CR_PLLRDY) == 0) /* (9) */
    // { /* For robust implementation, add here time-out management */ }
    // RCC->CFGR |= (uint32_t) (RCC_CFGR_SW_PLL); /* (10) */

    // while ((RCC->CFGR & RCC_CFGR_SWS) != RCC_CFGR_SWS_PLL) /* (11) */
    // { /* For robust implementation, add here time-out management */ }

    /*!< Reset
     * PLLSRC (HSI16 is the PLL source),
     * PLLMUL[3:0] (3x PLL multiplication)
     * Don't touch PLLDIV[1:0], since 0 is undefined
     */
    CLR(RCC->CFGR,
        RCC_CFGR_PLLSRC | RCC_CFGR_PLLMUL | RCC_CFGR_PLLDIV);

    /*!< Disable all interrupts */
    RCC->CIER = 0x00000000;

    /* Vector Table Relocation in Internal FLASH */
    SCB->VTOR = FLASH_BASE;
}

extern "C" {

typedef void (*func_ptr)(void);
extern func_ptr __init_array_start[], __init_array_end[];

static void _init(void)
{

	for (func_ptr* func = __init_array_start; func != __init_array_end; func++) {
		(*func)();
    }
}
}

[[noreturn]] void main() {

    _init();

    // Set up the system clock
    BSP::RtcDriver::init();
    BSP::SystemTimer::set_timer(BSP::RtcDriver::get_system_timer());
    BSP::LowPower::init();

    // Initialize the tasks
    g_lptim_pwm.init();
    g_spi.init();
    g_btn_manager.init();
    g_display.init();
    g_screen_manager.init();
    g_screen_manager.set_root_screen(g_display_time_screen);

    // Enqueue each of the tasks
    BSP::Schedule::NextTime asap = BSP::Schedule::NextTime::asap();
    g_sched.add_task(g_spi, asap);
    g_sched.add_task(g_btn_manager, asap);
    g_sched.add_task(g_display, asap);
    g_sched.add_task(g_screen_manager, asap);

    // And we're off! This will never return
    g_sched.run();
}


extern "C" void NMI_Handler() {while (1);}
extern "C" void HardFault_Handler() {while (1);}
extern "C" void SVC_Handler() {while (1);}
extern "C" void PendSV_Handler() {while (1);}
extern "C" void SysTick_Handler() {while (1);}

extern "C" void WWDG_IRQHandler() {while (1);}
extern "C" void PVD_IRQHandler() {while (1);}
extern "C" void WDT_IRQHandler() {while (1);}
extern "C" void FLASH_IRQHandler() {while (1);}
extern "C" void RCC_CRS_IRQHandler() {while (1);}
extern "C" void DMA1_CHANNEL1_IRQHandler() {while (1);}
extern "C" void DMA1_CHANNEL3_2_IRQHandler() {while (1);}
extern "C" void DMA_CHANNEL_7_4_IRQHandler() {while (1);}
extern "C" void ADC_COMP_IRQHandler() {while (1);}
extern "C" void LPTIM1_IRQHandler() {while (1);}
extern "C" void USART4_USART5_IRQHandler() {while (1);}
extern "C" void TIM2_IRQHandler() {while (1);}
extern "C" void TIM3_IRQHandler() {while (1);}
extern "C" void TIM6_IRQHandler() {while (1);}
extern "C" void TIM7_IRQHandler() {while (1);}
extern "C" void TIM21_IRQHandler() {while (1);}
extern "C" void I2C3_IRQHandler() {while (1);}
extern "C" void TIM22_IRQHandler() {while (1);}
