#include "map.h"

#include <sstream>
#include <fstream>
#include <algorithm>

game_map::game_map(int lvl):
        layer{layer_num::map}, map{MAP_HEIGHT}, level{lvl} {
        // TODO: randomly generate a map
}

game_map::game_map(const std::string &map_data, int lvl):
        layer{layer_num::map}, map{MAP_HEIGHT}, level{lvl} {
        std::istringstream iss{map_data};

        std::string line;

        for (int i = 0; i < MAP_HEIGHT; ++i) {
                getline(iss, line);
                map.push_back(line);
        }
}

game_map::~game_map() {}

int game_map::get_level() const {
        return this->level;
}

std::vector<position> game_map::get_available_positions() const {
        std::vector<position> result;

        for (int line = 0; line < MAP_HEIGHT; ++line)
                for (int x = 0; x < MAP_WIDTH; ++x)
                        if (map[line][x] == '.')
                                result.push_back(position{x, line});
        return result;
}

void game_map::print() const {

        // TODO: write a print function using ncurses
}

void game_map::print(display &display) const {
        for (int i = 0; i < MAP_HEIGHT; ++i)
                display.print_line(map[i] + "\n", i);
}

void game_map::apply_potion(character *who, const stat_name statn,
                            const int amount) {
        effects.push_back(effect{who, statn, amount});
        who->apply_buff(statn, amount);
}

void game_map::enter_level(character *who) {
        for (auto eff : effects)
                if (eff.who == who)
                        who->apply_buff(eff.statn, eff.amount);
}

void game_map::leave_level(character *who) {
        who->set_ATK(STARTING_ATK[who->get_race()]);
        who->set_DEF(STARTING_DEF[who->get_race()]);
}
