#include "amt/raycaster.hpp"
#include "amt/texture.hpp"
#include "amt/pixel.hpp"
#include "constants.hpp"
#include "thread.hpp"

#define AMT_LIGHT

using namespace fmt;


#ifdef AMT_LIGHT
static constexpr auto room_brightness = 0.3f; // increse this to increase the room brightness. Higher value means brighter room.

inline static constexpr amt::RGBA dumb_lighting(amt::RGBA pixel, float distance, float distance_from_center) {
  auto const dim_pixel = pixel * room_brightness;
  if (distance_from_center >= 0) {
    auto const min_brightness = 1.f / std::max(distance_from_center, 0.5f); // farther away from the center darker it gets
    auto const max_brightness = 1.f; // brighness should not exceed 1
    auto const pixel_brightness = std::max(min_brightness, std::min(max_brightness, distance));

    auto const yellow_brightness = float(distance_from_center * 60);
    amt::RGBA const yellow = amt::HSLA(40, 20, yellow_brightness);

    auto temp = (pixel / pixel_brightness).blend<amt::BlendMode::softLight>(yellow);
    return temp.brightness() < 0.1f ? dim_pixel : temp;
  } else {
    return dim_pixel;
  }
}
#else
inline static constexpr amt::RGBA dumb_lighting(amt::RGBA pixel, double distance, double distance_from_center) {
  (void)distance_from_center;
  if(distance < 0.9) return pixel;
  return pixel / distance;
}
#endif


Raycaster::Raycaster(sf::RenderWindow& window, Matrix &map, unsigned width, unsigned height) :
  view_texture(sf::Vector2u{width, height}),
  view_sprite(view_texture),
  $width(static_cast<int>(width)),
  $height(static_cast<int>(height)),
  pixels(height, width),
  $window(window),
  $map(map),
  spriteOrder(textures.NUM_SPRITES),
  spriteDistance(textures.NUM_SPRITES),
  ZBuffer(width),
  $radius(std::min($height, $width) / 2),
  $r_sq($radius * $radius)
{
  $window.setVerticalSyncEnabled(VSYNC);
  view_sprite.setPosition({0, 0});
  textures.load_textures();
}

void Raycaster::set_position(int x, int y) {
  view_sprite.setPosition({(float)x, (float)y});
}

void Raycaster::position_camera(float player_x, float player_y) {
  // x and y start position
  posX = player_x;
  posY = player_y;
}

void Raycaster::draw_pixel_buffer() {
  view_texture.update(pixels.to_raw_buf(), {(unsigned int)$width, (unsigned int)$height}, {0, 0});
  $window.draw(view_sprite);
}

void Raycaster::clear() {
  pixels.fill({});
  $window.clear();
}

void Raycaster::sprite_casting() {
  // sort sprites from far to close
  for(int i = 0; i < textures.NUM_SPRITES; i++) {
    auto& sprite = textures.get_sprite(i);
    spriteOrder[i] = i;
    // this is just the distance calculation
    spriteDistance[i] = ((posX - sprite.x) *
        (posX - sprite.x) +
        (posY - sprite.y) *
        (posY - sprite.y));
  }

  sort_sprites(spriteOrder, spriteDistance, textures.NUM_SPRITES);

  /*for(int i = 0; i < textures.NUM_SPRITES; i++) {*/
  // after sorting the sprites, do the projection
  // Be careful about capturing stack variables.
  amt::parallel_for<1>(pool, 0, textures.NUM_SPRITES, [this, textureWidth = textures.TEXTURE_WIDTH, textureHeight = textures.TEXTURE_HEIGHT](size_t i){
    int sprite_index = spriteOrder[i];
    Sprite& sprite_rec = textures.get_sprite(sprite_index);
    auto& sprite_texture = textures.get_texture(sprite_rec.texture);

    double spriteX = sprite_rec.x - posX;
    double spriteY = sprite_rec.y - posY;

    //transform sprite with the inverse camera matrix
    // [ planeX   dirX ] -1                                       [ dirY      -dirX ]
    // [               ]       =  1/(planeX*dirY-dirX*planeY) *   [                 ]
    // [ planeY   dirY ]                                          [ -planeY  planeX ]

    double invDet = 1.0 / (planeX * dirY - dirX * planeY); // required for correct matrix multiplication

    double transformX = invDet * (dirY * spriteX - dirX * spriteY);
    //this is actually the depth inside the screen, that what Z is in 3D, the distance of sprite to player, matching sqrt(spriteDistance[i])

    double transformY = invDet * (-planeY * spriteX + planeX * spriteY);

    int spriteScreenX = int(($width / 2) * (1 + transformX / transformY));

    int vMoveScreen = int(sprite_rec.elevation * -1 / transformY);

    // calculate the height of the sprite on screen
    //using "transformY" instead of the real distance prevents fisheye
    int spriteHeight = abs(int($height / transformY)) / sprite_rec.vDiv;

    //calculate lowest and highest pixel to fill in current stripe
    int drawStartY = -spriteHeight / 2 + $height / 2 + vMoveScreen;
    if(drawStartY < 0) drawStartY = 0;
    int drawEndY = spriteHeight / 2 + $height / 2 + vMoveScreen;
    if(drawEndY >= $height) drawEndY = $height - 1;

    // calculate width the the sprite
    // same as height of sprite, given that it's square
    int spriteWidth = abs(int($height / transformY)) / sprite_rec.uDiv;
    int drawStartX = -spriteWidth / 2 + spriteScreenX;
    if(drawStartX < 0) drawStartX = 0;
    int drawEndX = spriteWidth / 2 + spriteScreenX;
    if(drawEndX > $width) drawEndX = $width;

    //loop through every vertical stripe of the sprite on screen
    for(int stripe = drawStartX; stripe < drawEndX; stripe++) {
      int texX = int(256 * (stripe - (-spriteWidth / 2 + spriteScreenX)) * textureWidth / spriteWidth) / 256;
      // the conditions in the if are:
      // 1) it's in front of the camera plane so you don't see things behind you
      // 2) ZBuffer, with perpendicular distance
      if (texX < 0) continue;
      if(transformY > 0 && transformY < ZBuffer[stripe]) {
        for(int y = drawStartY; y < drawEndY; y++) {
          //256 and 128 factors to avoid floats
          int d = (y - vMoveScreen) * 256 - $height * 128 + spriteHeight * 128;
          int texY = ((d * textureHeight) / spriteHeight) / 256;
          if ((size_t)texY >= sprite_texture.rows()) continue;
          //get current color from the texture
          auto color = sprite_texture[texY][texX];
          // poor person's transparency, get current color from the texture
          if (!(color.to_hex() & 0xffffff00)) continue;
          auto dist = get_distance_from_center(stripe, y);
          pixels[y][stripe] = dumb_lighting(color, d, dist);
        }
      }
    }
   });
}

float Raycaster::get_distance_from_center(int x, int y) const noexcept {
  float cx = $width / 2;
  float cy = $height / 2;
  auto dx = cx - x;
  auto dy = cy - y;
  return ($r_sq - dx * dx - dy * dy) / $r_sq;
}

void Raycaster::cast_rays() {

  // WALL CASTING
  /*for(int x = 0; x < $width; x++) {*/
  amt::parallel_for<32>(pool, 0, static_cast<std::size_t>($width), [this](size_t x){
    double perpWallDist = 0;
    // calculate ray position and direction
    double cameraX = 2 * x / double($width) - 1; // x-coord in camera space
    double rayDirX = dirX + planeX * cameraX;
    double rayDirY = dirY + planeY * cameraX;

    // which box of the map we're in
    int mapX = int(posX);
    int mapY = int(posY);

    // length of ray from current pos to next x or y-side
    double sideDistX;
    double sideDistY;

    // length of ray from one x or y-side to next x or y-side
    double deltaDistX = std::abs(1.0 / rayDirX);
    double deltaDistY = std::abs(1.0 / rayDirY);

    int stepX = 0;
    int stepY = 0;
    int hit = 0;
    int side = 0;

    // calculate step and initial sideDist
    if(rayDirX < 0) {
      stepX = -1;
      sideDistX = (posX - mapX) * deltaDistX;
    } else {
      stepX = 1;
      sideDistX = (mapX + 1.0 - posX) * deltaDistX;
    }

    if(rayDirY < 0) {
      stepY = -1;
      sideDistY = (posY - mapY) * deltaDistY;
    } else {
      stepY = 1;
      sideDistY = (mapY + 1.0 - posY) * deltaDistY;
    }

    // perform DDA
    while(hit == 0) {
      if(sideDistX < sideDistY) {
        sideDistX += deltaDistX;
        mapX += stepX;
        side = 0;
      } else {
        sideDistY += deltaDistY;
        mapY += stepY;
        side = 1;
      }

      if($map[mapY][mapX] > 0) hit = 1;
    }

    if(side == 0) {
      perpWallDist = (sideDistX - deltaDistX);
    } else {
      perpWallDist = (sideDistY - deltaDistY);
    }

    int lineHeight = int($height / perpWallDist);

    int drawStart = -lineHeight / 2 + $height / 2 + PITCH;
    if(drawStart < 0) drawStart = 0;

    int drawEnd = lineHeight / 2 + $height / 2 + PITCH;
    if(drawEnd >= $height) drawEnd = $height - 1;

    auto &texture = textures.get_texture($map[mapY][mapX] - 1);

    // calculate value of wallX
    double wallX;  // where exactly the wall was hit
    if(side == 0) {
      wallX = posY + perpWallDist * rayDirY;
    } else {
      wallX = posX + perpWallDist * rayDirX;
    }
    wallX -= floor((wallX));

    // x coorindate on the texture
    int texX = int(wallX * double(textures.TEXTURE_WIDTH));
    if(side == 0 && rayDirX > 0) texX = textures.TEXTURE_WIDTH - texX - 1;
    if(side == 1 && rayDirY < 0) texX = textures.TEXTURE_WIDTH - texX - 1;

    // LODE: an integer-only bresenham or DDA like algorithm could make the texture coordinate stepping faster

    // How much to increase the texture coordinate per screen pixel
    double step = 1.0 * textures.TEXTURE_HEIGHT / lineHeight;
    // Starting texture coordinate
    double texPos = (drawStart - PITCH - $height / 2 + lineHeight / 2) * step;

    for(int y = drawStart; y < drawEnd; y++) {
      int texY = (int)texPos & (textures.TEXTURE_HEIGHT - 1);
      texPos += step;
      auto dist = get_distance_from_center(x, y);
      auto color = dumb_lighting(texture[texY][texX], perpWallDist, dist);
      pixels[y][x] = color;
    }

    // SET THE ZBUFFER FOR THE SPRITE CASTING
    ZBuffer[x] = perpWallDist;
  });
}

void Raycaster::draw_ceiling_floor() {

  /*for(int y = $height / 2 + 1; y < $height; ++y) {*/

  auto const h = static_cast<size_t>($height);
  amt::parallel_for<32>(pool, h / 2, h, [this, $height=h](size_t y){
    const size_t textureWidth = textures.TEXTURE_WIDTH;
    const size_t textureHeight = textures.TEXTURE_HEIGHT;
    // rayDir for leftmost ray (x=0) and rightmost (x = w)
    float rayDirX0 = dirX - planeX;
    float rayDirY0 = dirY - planeY;
    float rayDirX1 = dirX + planeX;
    float rayDirY1 = dirY + planeY;

    // current y position compared to the horizon
    int p = y - $height / 2;

    // vertical position of the camera
    // 0.5 will the camera at the center horizon. For a
    // different value you need a separate loop for ceiling
    // and floor since they're no longer symmetrical.
    float posZ = 0.5 * $height;

    // horizontal distance from the camera to the floor for the current row
    // 0.5 is the z position exactly in the middle between floor and ceiling
    // See NOTE in Lode's code for more.
    float rowDistance = posZ / p;

    // calculate the real world step vector we have to add for each x (parallel to camera plane)
    // adding step by step avoids multiplications with a wight in the inner loop
    float floorStepX = rowDistance * (rayDirX1 - rayDirX0) / $width;
    float floorStepY = rowDistance * (rayDirY1 - rayDirY0) / $width;


    // real world coordinates of the leftmost column.
    // This will be updated as we step to the right
    float floorX = posX + rowDistance * rayDirX0;
    float floorY = posY + rowDistance * rayDirY0;

    for(int x = 0; x < $width; ++x) {
      // the cell coord is simply taken from the int parts of
      // floorX and floorY.
      int cellX = int(floorX);
      int cellY = int(floorY);

      // get the texture coordinat from the fractional part
      int tx = int(textureWidth * (floorX - cellX)) & (textureWidth - 1);
      int ty = int(textureWidth * (floorY - cellY)) & (textureHeight - 1);

      floorX += floorStepX;
      floorY += floorStepY;

      // now get the pixel from the texture
      // this uses the previous ty/tx fractional parts of
      // floorX cellX to find the texture x/y. How?

      #ifdef AMT_LIGHT
      // FLOOR
      auto dist_floor = get_distance_from_center(x, y);
      pixels[y][x] = dumb_lighting(textures.floor[ty][tx], p, dist_floor);

      // CEILING
      auto dist_ceiling = get_distance_from_center(x, $height - y - 1);
      pixels[$height - y - 1][x] = dumb_lighting(textures.ceiling[ty][tx], p, dist_ceiling);
      #else
      // FLOOR
      pixels[y][x] = textures.floor[ty][tx];

      // CEILING
      pixels[$height - y - 1][x] = textures.ceiling[ty][tx];
      #endif

    }
  });

}

void Raycaster::render() {
  draw_ceiling_floor();
  // This wait to prevent data-race
  pool.wait(); // Try to remove this to see unbelievable performance
  cast_rays();
  pool.wait(); // Try to remove this too
  sprite_casting();
  pool.wait();
  draw_pixel_buffer();
}

bool Raycaster::empty_space(int new_x, int new_y) {
  dbc::check((size_t)new_x < $map.cols(),
      format("x={} too wide={}", new_x, $map.cols()));
  dbc::check((size_t)new_y < $map.rows(),
      format("y={} too high={}", new_y, $map.rows()));

  return $map[new_y][new_x] == 0;
}


void Raycaster::sort_sprites(std::vector<int>& order, std::vector<double>& dist, int amount)
{
  std::vector<std::pair<double, int>> sprites(amount);

  for(int i = 0; i < amount; i++) {
    sprites[i].first = dist[i];
    sprites[i].second = order[i];
  }

  std::sort(sprites.begin(), sprites.end());

  // restore in reverse order
  for(int i = 0; i < amount; i++) {
    dist[i] = sprites[amount - i - 1].first;
    order[i] = sprites[amount - i - 1].second;
  }
}

void Raycaster::run(double speed, int dir) {
  double speed_and_dir = speed * dir;
  if(empty_space(int(posX + dirX * speed_and_dir), int(posY))) {
    posX += dirX * speed_and_dir;
  }

  if(empty_space(int(posX), int(posY + dirY * speed_and_dir))) {
      posY += dirY * speed_and_dir;
  }
}

void Raycaster::rotate(double speed, int dir) {
  double speed_and_dir = speed * dir;
  double oldDirX = dirX;
  dirX = dirX * cos(speed_and_dir) - dirY * sin(speed_and_dir);
  dirY = oldDirX * sin(speed_and_dir) + dirY * cos(speed_and_dir);

  double oldPlaneX = planeX;
  planeX = planeX * cos(speed_and_dir) - planeY * sin(speed_and_dir);
  planeY = oldPlaneX * sin(speed_and_dir) + planeY * cos(speed_and_dir);
}
