#include <cstdint>
#include <cstdio>

#include "main.h"
#include "gui_task.h"
#include "task.h"
#include "st7789.h"
#include "tim.h"
#include "dac.h"

static const char* const TAG = "GUI";
static constexpr uint16_t delay_ms = 5000U;

//------------------------------------------------------------------------------

void guiTaskStart(void* argument)
{
	UNUSED(argument);

	vTaskDelay(5000U);

	//HAL_GPIO_WritePin(PWM_DISPLAY_LIGHT_GPIO_Port, PWM_DISPLAY_LIGHT_Pin, GPIO_PIN_SET);
	//HAL_GPIO_WritePin(RST_DISPLAY_GPIO_Port, RST_DISPLAY_Pin, GPIO_PIN_SET);

	ST7789_Initial();
	show_picture();

	if (HAL_TIM_PWM_Start(&htim1, TIM_CHANNEL_1) != HAL_OK) Error_Handler();
	if (HAL_TIMEx_PWMN_Start(&htim1, TIM_CHANNEL_1) != HAL_OK) Error_Handler();

	uint32_t min_pulse = __HAL_TIM_GET_COMPARE(&htim1, TIM_CHANNEL_1);
	constexpr decltype(min_pulse) max_pulse = 150;//555U;
	constexpr uint32_t d = 200U;

	for (auto i = min_pulse; i <= max_pulse; i++)
	{
		//__HAL_TIM_SET_COMPARE(&htim1, TIM_CHANNEL_1, i);
		htim1.Instance->CCR1 = i;
		vTaskDelay(pdMS_TO_TICKS(d));
	}

	for (auto i = 2047U; i < 2000U; i++)
	{
		HAL_StatusTypeDef r = HAL_DAC_SetValue(&hdac1, DAC_LOAD_I_LIMIT_CHANNEL, DAC_ALIGN_12B_R, i);
		if (r != HAL_OK) Error_Handler();
		vTaskDelay(pdMS_TO_TICKS(d));
	}

	while(1)
	{
		//ST7789_Write_Cmd_Data(0xFA);
		//HAL_GPIO_TogglePin(PWM_DISPLAY_LIGHT_GPIO_Port, PWM_DISPLAY_LIGHT_Pin);

		/*for (auto i = min_pulse; i <= max_pulse; i++)
		{
			//__HAL_TIM_SET_COMPARE(&htim1, TIM_CHANNEL_1, i);
			htim1.Instance->CCR1 = i;
			vTaskDelay(pdMS_TO_TICKS(d));
		}

		vTaskDelay(delay_ms);

		for (auto i = max_pulse; i >= min_pulse; i--)
		{
			//__HAL_TIM_SET_COMPARE(&htim1, TIM_CHANNEL_1, i);
			htim1.Instance->CCR1 = i;
			vTaskDelay(pdMS_TO_TICKS(d));
		}*/

		vTaskDelay(delay_ms);

		//printThreadStackInfo(TAG);
	}
}

//------------------------------------------------------------------------------
