/**
 * @file    ASYD_tinyK22_Blinky.c
 * @brief   Application entry point.
 */
#include <stdio.h>
#include "board.h"
#include "peripherals.h"
#include "pin_mux.h"
#include "clock_config.h"
#include "MK22F51212.h"
#include "fsl_debug_console.h"
#include "McuLib.h"
#include "McuWait.h"
#include "McuGPIO.h"
#include "McuLED.h"
#include "McuButton.h"
#include "McuRTOS.h"
#include "McuShell.h"
#include "McuShellUart.h"
#include "McuRTT.h"
#include "McuSystemView.h"

static McuLED_Handle_t tinyLED;
static McuBtn_Handle_t button;

#if McuLib_CONFIG_SDK_USE_FREERTOS
static void blinkyTask(void *pv) {
  for(;;) {
	McuLED_Toggle(tinyLED);
    vTaskDelay(pdMS_TO_TICKS(1000));
  }
}
#endif


static void blink(void) {
  for(;;) {
    McuLED_Toggle(tinyLED);
    if (McuBtn_IsOn(button)) {
      McuShell_SendStr((unsigned char*)"pressed!\n", McuShellUart_stdio.stdOut);
    }
    McuShell_SendStr((unsigned char*)"Hello World!\n", McuShellUart_stdio.stdOut);
    McuWait_Waitms(1000);
  }
}

static void init(void) {
  McuLib_Init();
  McuGPIO_Init();
  McuLED_Init();
  McuBtn_Init();
  McuWait_Init();
  McuRTT_Init();
  McuSystemView_Init();
  McuShell_Init();
  McuShellUart_Init();
  {
    McuLED_Config_t config;

    #define PINS_LEDBLUE_GPIO       GPIOC
    #define PINS_LEDBLUE_PORT       PORTC
    #define PINS_LEDBLUE_PIN        2U
    CLOCK_EnableClock(kCLOCK_PortC);
    McuLED_GetDefaultConfig(&config);
    config.isLowActive = true;
    config.hw.pin = PINS_LEDBLUE_PIN;
    config.hw.port = PINS_LEDBLUE_PORT;
    config.hw.gpio = PINS_LEDBLUE_GPIO;
    tinyLED = McuLED_InitLed(&config);
    if (tinyLED==NULL) {
      for(;;) {}
    }
  }
  {
    McuBtn_Config_t btnConfig;

    #define PINS_HATNAVPUSH_GPIO    GPIOB
    #define PINS_HATNAVPUSH_PORT    PORTB
    #define PINS_HATNAVPUSH_PIN     16u
    CLOCK_EnableClock(kCLOCK_PortB);
    btnConfig.hw.gpio = PINS_HATNAVPUSH_GPIO;
    btnConfig.hw.port = PINS_HATNAVPUSH_PORT;
    btnConfig.hw.pin = PINS_HATNAVPUSH_PIN;
    btnConfig.hw.pull = McuGPIO_PULL_UP;
    button = McuBtn_InitButton(&btnConfig);
  }
}

int main(void) {
    /* Init board hardware. */
    BOARD_InitBootPins();
    BOARD_InitBootClocks();
    BOARD_InitBootPeripherals();
#ifndef BOARD_INIT_DEBUG_CONSOLE_PERIPHERAL
    /* Init FSL debug console. */
    BOARD_InitDebugConsole();
#endif
    init();

    PRINTF("Hello World\n");
#if McuLib_CONFIG_SDK_USE_FREERTOS
    if (xTaskCreate(blinkyTask, "blinky", 500/sizeof(StackType_t), NULL, tskIDLE_PRIORITY, NULL)!=pdPASS) {
      for(;;) {}
    }
    vTaskStartScheduler();
#endif

    /* Force the counter to be placed into memory. */
    volatile static int i = 0 ;
    /* Enter an infinite loop, just incrementing a counter. */
    while(1) {
      blink();
      i++ ;
      /* 'Dummy' NOP to allow source level single stepping of
          tight while() loop */
      __asm volatile ("nop");
    }
    return 0 ;
}
