#include "constants.h"
#include "flame.h"

#include "overlay.h"

#define FLAME_PALETTE_SIZE 36

uint16_t flame_palette[] = {
    0x0020,
    0x1820,
    0x2860,
    0x4060,
    0x50A0,
    0x60E0,
    0x70E0,
    0x8920,
    0x9960,
    0xA9E0,
    0xBA20,
    0xC220,
    0xDA60,
    0xDAA0,
    0xDAA0,
    0xD2E0,
    0xD321,
    0xCB61,
    0xCBA1,
    0xCBE1,
    0xCC23,
    0xC422,
    0xC462,
    0xC4A3,
    0xBCE3,
    0xBCE3,
    0xBD24,
    0xBD24,
    0xBD65,
    0xB565,
    0xB5A5,
    0xB5A6,
    0xCE6D,
    0xDEF3,
    0xEF78,
    0xFFFF
};

int framebuffer[PANEL_WIDTH * PANEL_HEIGHT];
bool flame_ready = false;

void spread_fire(int from) {
  int rand = random(1, 4);
  int rand_y = random(-1, 2);
  int to = from - PANEL_WIDTH + rand_y;
  if (to < 0) {
    to = 0;
  }
  framebuffer[to] = framebuffer[from] - rand;
  if (framebuffer[to] < 0)
    framebuffer[to] = 0;
}

void do_fire() {
  for(int x = 0 ; x < PANEL_WIDTH; x++) {
    for (int y = 1; y < PANEL_HEIGHT ; y++) {
      spread_fire(y * PANEL_WIDTH + x);
    }
  }
}


void setup_flame() {
    memset(framebuffer, 0, sizeof framebuffer);
    //for (int i = 0; i < PANEL_WIDTH; i++) {
    //    framebuffer[(PANEL_WIDTH * PANEL_HEIGHT - i - 1)] = FLAME_PALETTE_SIZE - 1;
    //}
}

void draw_flame(MatrixPanel_I2S_DMA *matrix, enum Mode mode) {
  if(not flame_ready) {
    setup_flame();
    flame_ready = true;
  }
  for(int p = 0; p < PANEL_HEIGHT * PANEL_WIDTH; p++) {
    if (overlay[p / 8] & (1 << (7 - (p % 8))) and mode != Stealth) {
      // offset the text
        framebuffer[p + (6 * PANEL_WIDTH)] = FLAME_PALETTE_SIZE - 1;
    }
    matrix->drawPixel(p % PANEL_WIDTH, p / PANEL_WIDTH, flame_palette[framebuffer[p]]);
  }
  do_fire();
  delay(10);
}
