#include <Arduino_GFX_Library.h>
#include <Wire.h>
#include <Adafruit_MCP23X17.h>

#define GFX_BL 6  // default backlight pin, you may replace DF_GFX_BL to actual backlight pin

#define SPI_MISO 11
#define SPI_MOSI 13
#define SPI_SCLK 12

#define LCD_CS 10
#define LCD_DC 16
#define LCD_RST 10
#define LCD_HOR_RES 240
#define LCD_VER_RES 240

#define I2C_SDA 8
#define I2C_SCL 7

// MCP23017 I2C address (A2=0, A1=0, A0 depends on configuration, default 0x20)
#define MCP23017_ADDR 0x20

Adafruit_MCP23X17 mcp;

Arduino_DataBus* bus = new Arduino_ESP32SPI(LCD_DC /* DC */, LCD_CS /* CS */, SPI_SCLK /* SCK */, SPI_MOSI /* MOSI */, SPI_MISO /* MISO */);
Arduino_GFX *gfx = new Arduino_ST7789(
  bus, LCD_RST /* RST */, 0 /* rotation */, true /* IPS */,
  240 /* width */, 240 /* height */,
  0 /* col offset 1 */, 0 /* row offset 1 */);

// Optional: Initialize MCP23017 (e.g. to control LCD reset or other IO pins)
static void initMCP23017()
{
  if (!mcp.begin_I2C(MCP23017_ADDR))
  {
    // MCP23017 not found, skip configuration
    return;
  }

  // Example: configure GPA1 as output and set HIGH (matches EXIO1 usage on W10 board)
  // You can adjust or extend this according to your actual hardware usage.
  mcp.pinMode(1, OUTPUT);
  mcp.digitalWrite(1, HIGH);
}

/*******************************************************************************
 * End of Arduino_GFX setting
 ******************************************************************************/

void setup(void)
{
    // Initialize I2C and MCP23017 before using peripherals
    Wire.begin(I2C_SDA, I2C_SCL);
    initMCP23017();

    gfx->begin();
    gfx->fillScreen(BLACK);

#ifdef GFX_BL
    pinMode(GFX_BL, OUTPUT);
    digitalWrite(GFX_BL, HIGH);
#endif

    gfx->setCursor(10, 10);
    gfx->setTextColor(RED);
    gfx->println("LoRa AIOT Development Kit!");
    delay(5000); // 5 seconds
}

void loop()
{
    gfx->setCursor(random(gfx->width()), 20+random(gfx->height()));
    gfx->setTextColor(random(0xffff), random(0xffff));
    gfx->setTextSize(random(6) /* x scale */, random(6) /* y scale */, random(2) /* pixel_margin */);
    gfx->println("LoRa AIOT Development Kit!");

    delay(1000); // 1 second
}