#include <user_code.hpp>
#include <espmega_iot_lcd.hpp>

/**
 * @brief Sends stop bit to LCD.
 * 
 * This function sends a stop bit to the LCD. It is only enabled if the ENABLE_INTERNAL_LCD macro is defined.
 */
void lcd_send_stop_bit()
{
#ifdef ENABLE_INTERNAL_LCD
    Serial.write(0xFF);
    Serial.write(0xFF);
    Serial.write(0xFF);
#endif
}

/**
 * Sends a command to the LCD display.
 * 
 * @param command The command to send to the LCD display.
 */
void lcd_send_command(String command)
{
#ifdef ENABLE_INTERNAL_LCD
    lcd_send_stop_bit();
    Serial.print(command);
    lcd_send_stop_bit();
#endif
}

/**
 * @brief Resets the LCD display.
 * 
 * If ENABLE_INTERNAL_LCD is defined, sends a reset command to the LCD display.
 * 
 */
void lcd_reset()
{
#ifdef ENABLE_INTERNAL_LCD
    lcd_send_stop_bit();
    lcd_send_command("rest");
    lcd_send_stop_bit();
#endif
}

/**
 * Initializes the LCD display.
 */
void lcd_init()
{
#ifdef ENABLE_INTERNAL_LCD
    lcd_reset();
    delay(750);
#endif
}

/**
 * @brief Starts the upload process to the LCD.
 * 
 * @param size The size of the data to be uploaded.
 * @return true if the upload process started successfully, false otherwise.
 */
bool lcd_upload_start(size_t size)
{
    Serial.begin(115200);
    lcd_send_stop_bit();
    Serial.print("rest");
    lcd_send_stop_bit();
    Serial.print("connect");
    lcd_send_stop_bit();
    delay(1000);
    Serial.print("whmi-wri 1024,115200,res0");
    lcd_send_stop_bit();
    lcd_wait_ack();
}

/**
 * Writes data to the LCD upload buffer.
 * 
 * @param data Pointer to the data to be written.
 * @param size Size of the data to be written.
 * @return True if the write was successful, false otherwise.
 */
bool lcd_upload_write(uint8_t *data, size_t size)
{
    for (int i = 0; i < size; i++)
    {
        Serial.write(data[i]);
    }
}

/**
 * Waits for an acknowledgement signal from the LCD.
 * @return true if acknowledgement signal is received, false otherwise.
 */
bool lcd_wait_ack()
{
    bool data_ok = false;
    for (int i; i < 50; i++)
    {
        if (Serial.read() == 0x05)
        {
            data_ok = true;
            break;
        }
        delay(100);
    }
    return data_ok;
}