#ifndef MAP_H_3AB00D12
#define MAP_H_3AB00D12

#include <vector>
#include <algorithm>

template <typename T>
class Map {
public:

  Map(
    int left,
    int top,
    int width,
    int height) :
      left_(left),
      top_(top),
      width_(width),
      height_(height),
      data_(width_*height_)
  {
  }

  inline int getLeft() const
  {
    return left_;
  }

  inline int getRight() const
  {
    return left_ + width_;
  }

  inline int getTop() const
  {
    return top_;
  }

  inline int getBottom() const
  {
    return top_ + height_;
  }

  inline int getWidth() const
  {
    return width_;
  }

  inline int getHeight() const
  {
    return height_;
  }

  inline int getTrueX(int x) const
  {
    return (x - left_);
  }

  inline int getTrueY(int y) const
  {
    return (y - top_);
  }

  inline bool inBounds(int x, int y) const
  {
    return (x >= left_) &&
           (x < left_ + width_) &&
           (y >= top_) &&
           (y < top_ + height_);
  }

  inline const T& at(int x, int y) const
  {
    return data_.at((x - left_) + width_ * (y - top_));
  }

  inline T& at(int x, int y)
  {
    return const_cast<T&>(static_cast<const Map&>(*this).at(x, y));
  }

  inline const std::vector<T>& data() const
  {
    return data_;
  }

  inline std::vector<T>& data()
  {
    return data_;
  }

  void resize(int newLeft, int newTop, int newWidth, int newHeight)
  {
    std::vector<T> newData(newWidth * newHeight);

    int winTop = std::max(top_, newTop);
    int winBottom = std::min(top_ + height_, newTop + newHeight);
    int winLeft = std::max(left_, newLeft);
    int winRight = std::min(left_ + width_, newLeft + newWidth);

    for (int y = winTop; y < winBottom; y++)
    {
      std::move(
        std::next(std::begin(data_), (winLeft - left_) + width_ * (y - top_)),
        std::next(std::begin(data_), (winRight - left_) + width_ * (y - top_)),
        std::next(std::begin(newData),
          (winLeft - newLeft) + newWidth * (y - newTop)));
    }

    left_ = newLeft;
    top_ = newTop;
    width_ = newWidth;
    height_ = newHeight;
    data_.swap(newData);
  }

private:

  int left_;
  int top_;
  int width_;
  int height_;

  std::vector<T> data_;
};

#endif /* end of include guard: MAP_H_3AB00D12 */