#include "GTag6Display.h"

// Прямой доступ к регистрам GPIO (быстрый SET/CLR одного бита)
#define PIN_SET(p)  (GPIO.out_w1ts.val = (1u << (p)))
#define PIN_CLR(p)  (GPIO.out_w1tc.val = (1u << (p)))

inline void GTag6Display::busPulse_() {
    PIN_SET(pinClk_);
    PIN_CLR(pinClk_);
}

// Команды/данные команд: D/C бит, затем 8 бит MSB-first, обычные уровни.
void GTag6Display::send9MSB_(bool isData, uint8_t v) {
    if (isData) PIN_SET(pinDio_); else PIN_CLR(pinDio_);
    busPulse_();
    for (uint8_t m = 0x80; m; m >>= 1) {
        if (v & m) PIN_SET(pinDio_); else PIN_CLR(pinDio_);
        busPulse_();
    }
}

// Данные кадра: D/C = 1, затем 8 бит LSB-first, инвертированные уровни.
void GTag6Display::send9LSB_(uint8_t v) {
    PIN_SET(pinDio_);   // data bit
    busPulse_();
    for (uint8_t i = 0; i < 8; i++) {
        if (v & 0x01) PIN_CLR(pinDio_); else PIN_SET(pinDio_);
        v >>= 1;
        busPulse_();
    }
}

bool GTag6Display::startDisplayClock_() {
#if ESP_ARDUINO_VERSION_MAJOR >= 3
     // Снимаем предыдущую привязку пина к LEDC, если она была.
    // Без этого повторный ledcAttach() вернёт false и begin() упадёт.
    ledcDetach(pinDisplayClk_);
    delay(1);
    if (!ledcAttach(pinDisplayClk_, 29000, 8)) return false;
    ledcWrite(pinDisplayClk_, 128);
#else
    const uint8_t ch = 0;
    ledcSetup(ch, 29000, 8);
    ledcAttachPin(pinDisplayClk_, ch);
    ledcWrite(ch, 128);
#endif
    return true;
}

void GTag6Display::hwReset_() {
    PIN_SET(pinReset_);  delay(10);
    PIN_CLR(pinReset_);  delayMicroseconds(50);
    PIN_SET(pinReset_);  delay(50);
}

void GTag6Display::initLcd_() {
    pinMode(pinDio_, OUTPUT);
    pinMode(pinClk_, OUTPUT);
    pinMode(pinCs_,  OUTPUT);
    pinMode(pinReset_, OUTPUT);
    PIN_CLR(pinDio_);
    PIN_CLR(pinClk_);
    PIN_SET(pinCs_);
    PIN_SET(pinReset_);
    delay(10);

    hwReset_();

    // Очистка RAM значением 0xFF
    select_();
    send9MSB_(false, 0x11);
    send9MSB_(false, 0x2A); send9MSB_(true, 0x00); send9MSB_(true, 0x00);
    send9MSB_(false, 0x2C);
    for (uint16_t i = 0; i < FRAME_SIZE; i++) send9MSB_(true, 0xFF);
    deselect_();
    delay(10);

    select_();
    send9MSB_(false, 0x4C);
    send9MSB_(true, 0x0C); send9MSB_(true, 0x00); send9MSB_(true, 0x00);
    deselect_();
    delay(4);

    select_();
    send9MSB_(false, 0x4D);
    send9MSB_(true, 0xFF); send9MSB_(true, 0x00); send9MSB_(true, 0x7F);
    deselect_();
    delay(1);

    select_();
    send9MSB_(false, 0x4E);
    send9MSB_(true, 0x60);
    deselect_();
}

bool GTag6Display::begin() {
    if (!startDisplayClock_()) return false;
    delay(100);
    initLcd_();
    clear(false);
    return true;
}

void GTag6Display::clear(bool black) {
    memset(fb_, black ? 0xFF : 0x00, FRAME_SIZE);
}

void GTag6Display::show() {
    select_();
    send9MSB_(false, 0x2A); send9MSB_(true, 0x00); send9MSB_(true, 0x00);
    send9MSB_(false, 0x2C);
    for (uint16_t i = 0; i < FRAME_SIZE; i++) send9LSB_(fb_[i]);
    deselect_();
}

void GTag6Display::hline(int x, int y, int w, bool black) {
    for (int i = 0; i < w; i++) pixel(x + i, y, black);
}
void GTag6Display::vline(int x, int y, int h, bool black) {
    for (int i = 0; i < h; i++) pixel(x, y + i, black);
}
void GTag6Display::rect(int x, int y, int w, int h, bool black) {
    if (w <= 0 || h <= 0) return;
    hline(x, y, w, black);
    hline(x, y + h - 1, w, black);
    vline(x, y, h, black);
    vline(x + w - 1, y, h, black);
}
void GTag6Display::fillRect(int x, int y, int w, int h, bool black) {
    for (int yy = 0; yy < h; yy++) hline(x, y + yy, w, black);
}