#include <main.h>
#include <spi.h>
#include <eeprom.h>
#include <string.h>
#include <logger.h>
#include <mbusComm.h>
#include <PontCoopScheduler.h>
#include <utils.h>

#define HIGH GPIO_PIN_SET
#define LOW GPIO_PIN_RESET



static const uint8_t EEPROM_READ = 0x03;
static const uint8_t EEPROM_WRITE = 0x02;
// static const uint8_t EEPROM_WRDI = 0x04;
static const uint8_t EEPROM_WREN = 0x06;
// static const uint8_t EEPROM_RDSR = 0x05;
// static const uint8_t EEPROM_WRSR = 0x01;


static const uint32_t EEPROM_MAGIC = 0xaffe0006;


typedef union {
  struct __attribute__((__packed__)) s_eepromHeader {
    uint32_t magic;
    uint32_t writeCounter;
    uint8_t activeBlock;
  } s;
  uint8_t b[sizeof(struct s_eepromHeader)];
} t_eepromHeader;

static const uint16_t EEPROM_HEADER_ADDR = 0;
static t_eepromHeader eepromHeader;

typedef union {
  struct __attribute__((__packed__)) s_deviceStats {
    uint32_t totalRunningHours;
    uint32_t totalPowercycles;
    uint32_t totalRequests;
    uint32_t totalFailures;
  } s;
  uint8_t b[sizeof(struct s_deviceStats)];
} t_deviceStats;

static const uint16_t DEVICE_STATS_ADDR = 32;
static t_deviceStats deviceStats;

static const uint8_t NUM_OF_BLOCKS = 2;
static const uint16_t BLOCK_ADDR[] = { 64, 4128 };


typedef union {
  struct __attribute__((__packed__)) s_spiMsg {
    uint8_t cmd;
    uint16_t addr;
    uint8_t data[32];
  } s;
  uint8_t b[sizeof(struct s_spiMsg)];
} t_spiMsg;



inline static void __EEPROM_CS(GPIO_PinState v) {
  HAL_GPIO_WritePin(EEPROM_CS_GPIO_Port, EEPROM_CS_Pin, v);
}

static uint16_t swap(uint16_t i) {
  return ((i & 0x00ff) << 8) | ((i & 0xff00) >> 8);
}


void eepromWrite(uint16_t addr, uint8_t *buf, uint8_t len) {
  t_spiMsg msg = {
    .s.cmd = EEPROM_WRITE,
    .s.addr = swap(addr)
  };
  memcpy(msg.s.data, buf, len);


  uint8_t writeEnable = EEPROM_WREN;
  __EEPROM_CS(LOW);
  HAL_SPI_Transmit(&eepromSpi, &writeEnable, 1, HAL_MAX_DELAY);
  __EEPROM_CS(HIGH);

  __EEPROM_CS(LOW);
  HAL_SPI_Transmit(&eepromSpi, msg.b, ((uint16_t)(len+3)), HAL_MAX_DELAY);
  __EEPROM_CS(HIGH);
}

void eepromRead(uint16_t addr, uint8_t *buf, uint8_t len) {
  t_spiMsg txMsg = {
    .s.cmd = EEPROM_READ,
    .s.addr = swap(addr)
  };

  t_spiMsg rxMsg;

  __EEPROM_CS(LOW);
  HAL_SPI_TransmitReceive(&eepromSpi, txMsg.b, rxMsg.b, ((uint16_t)(len+3)), HAL_MAX_DELAY);
  __EEPROM_CS(HIGH);

  memcpy(buf, rxMsg.s.data, len);
}

void eepromSpiTxCpltCallback(SPI_HandleTypeDef *hspi) {

}

static void eepromHourlyUpdateDeviceStats(void *handle) {
  deviceStats.s.totalRunningHours += 1;

  t_mbusCommStats *stats = mbusCommGetStats();

  deviceStats.s.totalRequests = stats->requestCnt;
  deviceStats.s.totalFailures = stats->errorCnt;

  logMsg("eeHUDS, about to write updated device stats");
  logMsg("eeHUDS, total powercycles so far: %d", deviceStats.s.totalPowercycles);
  logMsg("eeHUDS, total running hours so far: %d", deviceStats.s.totalRunningHours);
  logMsg("eeHUDS, total requests so far: %d", deviceStats.s.totalRequests);
  logMsg("eeHUDS, total failures so far: %d", deviceStats.s.totalFailures);

  eepromWrite(DEVICE_STATS_ADDR, deviceStats.b, sizeof(deviceStats));
}

// active waiting, use only during initialization!
static void eepromActiveDelay(uint8_t delay_ms) {
  activeDelay(delay_ms);
}

void eepromInit() {
  __EEPROM_CS(HIGH);

  logMsg("eeI, read header");
  eepromRead(EEPROM_HEADER_ADDR, eepromHeader.b, sizeof(eepromHeader));
  logMsg("eeI, magic: %08x", eepromHeader.s.magic);

  if (eepromHeader.s.magic != EEPROM_MAGIC) {
    logMsg("eeI, eeprom is uninitialized");

    deviceStats.s.totalPowercycles = 0;
    deviceStats.s.totalRunningHours = 0;
    deviceStats.s.totalRequests = 0;
    deviceStats.s.totalFailures = 0;
    logMsg("eeI, about to write device stats for the first time");
    eepromWrite(DEVICE_STATS_ADDR, deviceStats.b, sizeof(deviceStats));
    eepromActiveDelay(7);

    uint8_t emptyBlock[32];
    memset(emptyBlock, 0, sizeof(emptyBlock));
    for (uint8_t i = 0; i < NUM_OF_BLOCKS; i++) {
      for (uint8_t j = 0; j <= 127; j++) {
        uint16_t addr = BLOCK_ADDR[i] + sizeof(emptyBlock) * j;
        eepromWrite(addr, emptyBlock, sizeof(emptyBlock));
        eepromActiveDelay(7);
      }
    }
    logMsg("eeI, storage blocks initialized");


    eepromHeader.s.magic = EEPROM_MAGIC;
    eepromHeader.s.activeBlock = 0;
    eepromHeader.s.writeCounter = 1;
    logMsg("eeI, about to write header for the first time");
    eepromWrite(EEPROM_HEADER_ADDR, eepromHeader.b, sizeof(eepromHeader));
    eepromActiveDelay(7);
    logMsg("eeI, eeprom has been initialized");
  } else {
    logMsg("eeI, eeprom is initialized");
  }

  logMsg("eeI, about to read device stats");
  eepromRead(DEVICE_STATS_ADDR, deviceStats.b, sizeof(deviceStats));
  logMsg("eeI, total powercycles so far: %d", deviceStats.s.totalPowercycles);
  logMsg("eeI, total running hours so far: %d", deviceStats.s.totalRunningHours);
  logMsg("eeI, total requests so far: %d", deviceStats.s.totalRequests);
  logMsg("eeI, total failures so far: %d", deviceStats.s.totalFailures);

  t_mbusCommStats stats = { .requestCnt = deviceStats.s.totalRequests, .errorCnt = deviceStats.s.totalFailures};
  mbusCommSetStats(stats);

  deviceStats.s.totalPowercycles += 1;
  logMsg("eeI, about to write device stats with updated power cycles counter");
  eepromWrite(DEVICE_STATS_ADDR, deviceStats.b, sizeof(deviceStats));
  eepromActiveDelay(7);

  schAdd(eepromHourlyUpdateDeviceStats, NULL, 0, 60 * 60 * 1000);
  logMsg("eeI, hourly device stats update scheduled");
}