#include "render.hpp"
#include "ansi_parser.hpp"
#include <cmath>
#include <fmt/core.h>
#include <array>
#include "map.hpp"
#include <iostream>

using namespace fmt;

std::array<sf::Color, 10> VALUES{
  sf::Color{1, 4, 2},  // black
  sf::Color{9, 29, 16}, // dark dark
  sf::Color{14, 50, 26}, // dark mid
  sf::Color{0, 109, 44}, // dark light
  sf::Color{63, 171, 92}, // mid
  sf::Color{161, 217, 155}, // light dark
  sf::Color{199, 233, 192}, // light mid
  sf::Color{229, 245, 224}, // light light
  sf::Color{255, 255, 255}, // white
  sf::Color::Transparent, // white
};

sf::Color SFMLRender::color(int val) {
  return VALUES[size_t(val)];
}

sf::Color SFMLRender::color(Value val) {
  return VALUES[size_t(val)];
}

SFMLRender::SFMLRender() :
  $window(sf::VideoMode(VIDEO_X,VIDEO_Y), "Roguish"),
  $map_font_size(0),
  $line_spacing(0),
  $default_fg(color(Value::LIGHT_MID)),
  $default_bg(color(Value::BLACK)),
  $ansi($default_fg, $default_bg)
{
  // force true color, but maybe I want to support different color sets
  $font.loadFromFile("./assets/text.otf");
  $ui_text.setFont($font);
  $ui_text.setPosition(0,0);
  $ui_text.setCharacterSize(UI_FONT_SIZE);
  $ui_text.setFillColor(color(Value::LIGHT_MID));
  sf::Glyph glyph = $font.getGlyph(L'█', UI_FONT_SIZE, false);
  $ui_bounds = glyph.bounds;
}

sf::Sprite &SFMLRender::get_text_sprite(wchar_t tile) {
  if(!$sprites.contains(tile)) {
    sf::Glyph glyph = $font.getGlyph(tile, $map_font_size, false);
    // WARNING! we actually have to do this here because SFML caches
    // the glyphs on the font texture, so this gets loaded each time
    // we get a new glyph from the font.
    $font_texture = $font.getTexture($map_font_size);
    sf::Sprite sprite($font_texture);
    sprite.setTextureRect(glyph.textureRect);
    $sprites[tile] = sprite;
  }

  return $sprites[tile];
}

inline bool base_glyph_check(sf::Font &font, sf::Glyph &base_glyph, Point &view_port, int &font_size, int new_size) {
  auto glyph = font.getGlyph(BG_TILE, new_size, false);

  int view_x = std::ceil((VIDEO_X - GAME_MAP_POS) / glyph.bounds.width);
  int view_y = std::ceil(VIDEO_Y / glyph.bounds.height);

  // don't allow resizing beyond/below game map size
  if(view_x <= GAME_MAP_X && view_y <= GAME_MAP_Y) {
    // looks good, set 'em all
    base_glyph = glyph;
    view_port = {size_t(view_x), size_t(view_y)};
    font_size = new_size;
    return true;
  } else {
    return false;
  }
}


bool SFMLRender::resize_map(int new_size, Point &view_port) {
  if($map_font_size == new_size || new_size < MIN_FONT_SIZE || new_size > MAX_FONT_SIZE) return false;

  if(base_glyph_check($font, $base_glyph, view_port, $map_font_size, new_size)) {
    $sprites.clear(); // need to reset the sprites for the new size
    $line_spacing = $font.getLineSpacing($map_font_size);
    $bg_sprite = get_text_sprite(BG_TILE);
    $bg_bounds = $bg_sprite.getLocalBounds();
    return true;
  } else {
    // something else here
    return false;
  }
}

inline void configure_tile(const sf::Sprite &sprite, sf::FloatRect &sp_bounds,  sf::FloatRect bg_bounds, float &width_delta, float &height_delta) {
  // should look into caching all this instead of calcing it each time
  sp_bounds = sprite.getLocalBounds();

  // calculate where to center the sprite, but only if it's smaller
  width_delta = bg_bounds.width > sp_bounds.width ? (bg_bounds.width - sp_bounds.width) / 2 : 0;
  height_delta = bg_bounds.height > sp_bounds.width ? (bg_bounds.height - sp_bounds.height) / 2 : 0;
}

void SFMLRender::render_grid(const std::wstring &text, float x, float y) {
  wchar_t last_tile = '#';
  sf::FloatRect sp_bounds;
  float width_delta = 0;
  float height_delta = 0;
  sf::Sprite &sprite = get_text_sprite(last_tile);
  const float start_x = x;
  sf::Color cur_fg = $default_fg;

  // make a copy so we don't modify the cached one
  $ansi.parse(text, [&](sf::Color fg, sf::Color bg) {
      cur_fg = fg;
      $bg_sprite.setColor(bg);
    },

    [&](wchar_t tile) {
      if(tile == '\n') {
        // don't bother processing newlines, just skip
        y += $line_spacing;
        x = start_x;
      } else if(tile == L'\r') {
          return; // skip these, just windows junk
      } else {
        $bg_sprite.setPosition({x, y});

        // only get a new sprite if the tile changed
        if(last_tile != tile) {
          last_tile = tile; // update last tile seen
          sprite = get_text_sprite(tile);
          configure_tile(sprite, sp_bounds, $bg_bounds, width_delta, height_delta);
        }

        sprite.setPosition({x+width_delta, y+height_delta});
        sprite.setColor(cur_fg);

        $window.draw($bg_sprite);
        $window.draw(sprite);
        // next cell
        x += $base_glyph.advance;
      }
  });
}

inline sf::FloatRect draw_chunk(sf::RenderWindow& window, sf::Text& text, float x, float y, std::wstring &out) {
  text.setString(out);
  text.setPosition(x, y);
  sf::FloatRect bounds = text.getLocalBounds();
  // need left,top,width,height for box to be accurate
  window.draw(text);
  out.clear();
  return bounds;
}

void SFMLRender::render_text(const std::wstring &text, float start_x, float start_y) {
  std::wstring out;
  float x = start_x;
  float y = start_y;
  enum State { START=1, BUILDING=2 };
  enum Event { NL=1, CHAR=3, SKIP=5 };
  State state = START;
  Event event = CHAR;

  // start with the default_fg until it's changed
  $ui_text.setFillColor($default_fg);

  $ansi.parse(text,
    [&](sf::Color fg, sf::Color bg){
        if(out.size() > 0 ) {
          auto bounds = draw_chunk($window, $ui_text, x, y, out);
          x += bounds.width;
        }
        $ui_text.setFillColor(fg);
    },
    [&](wchar_t tile) {
      if(tile == '\r') event = SKIP;
      else if(tile == '\n') event = NL;
      else event = CHAR;

      switch(event) {
        case SKIP: break; // ignore it
        case NL: {
          if(state == START) {
            state = BUILDING;
          } else if(state == BUILDING) {
            sf::FloatRect bounds;

            if(out.size() > 0) {
              bounds = draw_chunk($window, $ui_text, x, y, out);
            } else {
              bounds = $ui_text.getLocalBounds();
            }

            y += bounds.height;
            x = start_x; // reset to the original position
          }
        }
        break;
        case CHAR:
          state = BUILDING;
          out += tile;
          break;
      }
    }
  );
}

void SFMLRender::draw_text(Panel &panel, bool with_border) {
  sf::RectangleShape backing(
      sf::Vector2f($ui_bounds.width * panel.width,
        $ui_bounds.height * panel.height));

  backing.setFillColor(sf::Color(0, 0, 0));

  if(with_border) {
    backing.setOutlineColor(color(Value::MID));
    backing.setOutlineThickness(5);
  }

  backing.setPosition(panel.x, panel.y);
  $window.draw(backing);

  panel.render();
  const std::wstring &panelout = panel.to_string();
  render_text(panelout, panel.x, panel.y);
}

void SFMLRender::draw_grid(Panel &panel, float x, float y) {
  panel.render();
  const std::wstring &panelout = panel.to_string();
  render_grid(panelout, panel.x + x, panel.y + y);
}
