#include "matrix.hpp"
#include "dbc.hpp"
#include <fmt/core.h>
#include <cmath>
#include <cstdlib>
#include "constants.hpp"

using namespace fmt;
using std::min, std::max;

namespace matrix {

  flood::flood(Matrix &mat, Point start, int old_val, int new_val) :
    mat(mat), start(start), old_val(old_val), new_val(new_val),
     x(start.x), y(start.y), dirs{mat, start.x, start.y}
  {
    dbc::check(old_val != new_val, "what you doing?");
    current_loc = start;
    q.push(start);
  }

  bool flood::next() {
    if(!q.empty()) {
      if(!dirs.next()) {
        // box is done reset it
        auto current_loc = q.front();
        q.pop();

        dirs = matrix::compass{mat, current_loc.x, current_loc.y};
        dirs.next();
      }

      // get the next thing
      if(mat[dirs.y][dirs.x] <= old_val) {
        mat[dirs.y][dirs.x] = new_val;
        x = dirs.x;
        y = dirs.y;

        q.push({.x=dirs.x, .y=dirs.y});
      }

      return true;
    } else {
      return false;
    }
  }

  line::line(Point start, Point end) :
      x(start.x), y(start.y),
      x1(end.x), y1(end.y)
  {
    dx = std::abs(x1 - x);
    sx = x < x1 ? 1 : -1;
    dy = std::abs(y1 - y) * -1;
    sy = y < y1 ? 1 : -1;
    error = dx + dy;
  }

  bool line::next() {
    if(x != x1 || y != y1) {
      int e2 = 2 * error;

      if(e2 >= dy) {
        error = error + dy;
        x = x + sx;
      }

      if(e2 <= dx) {
        error = error + dx;
        y = y + sy;
      }
      return true;
    } else {
      return false;
    }
  }

  void dump(const std::string &msg, Matrix &map, int show_x, int show_y) {
    println("----------------- {}", msg);

    for(each_row it{map}; it.next();) {
      int cell = map[it.y][it.x];

      if(int(it.x) == show_x && int(it.y) == show_y) {
        print("{:x}<", cell);
      } else if(cell == WALL_PATH_LIMIT) {
        print("# ");
      } else if(cell > 15) {
        print("* ");
      } else {
        print("{:x} ", cell);
      }

      if(it.row) print("\n");
    }
  }
}
