#ifndef INCLUDEPLAYER_H
#define INCLUDEPLAYER_H

#include "units/unit.h"
#include "racemanager.h"

#include <QObject>
#include <QDebug>

#include <set>

class Race;

template<class Obj, class Identifier>
class ObjectFactory;

class Player {
    struct unit_comparator {
        bool operator() (const std::shared_ptr<Unit> lhs, const std::shared_ptr<Unit> rhs) const {
            if (rhs == nullptr)
                return true;
            if (lhs->getUnitBaseClassId() != rhs->getUnitBaseClassId())
                return lhs->getUnitBaseClassId() < rhs->getUnitBaseClassId();
            return lhs->getUnitId() < rhs->getUnitId();
        }
    };

public:
    Player() {
        init(1);
    }

    void init(int id) {
        player_name_ = "Игрок " + QString::number(id + 1);
        race_ = RaceManager::getInstance().getRace(
                    RaceManager::getInstance().getAvailableRacesList()[0]
                );
        units_.clear();
    }

    QString getPlayerName() {
        return player_name_;
    }

    const std::multiset<std::shared_ptr<Unit>, unit_comparator>& getUnits() {
        return units_;
    }

    std::vector<std::shared_ptr<Unit>> getUnitsAsVector() {
        std::vector<std::shared_ptr<Unit>> result;
        for (auto unit: units_)
            result.push_back(unit);
        return result;
    }

    void addUnit(std::shared_ptr<Unit> a) {
        if (units_.size() >= 10)
            return;
        units_.insert(a);
    }

    void deleteUnit(std::shared_ptr<Unit> a) {
        qDebug() << "deleting unit " << a->getUnitName();
        auto unit = units_.find(a);
        if (unit != units_.end())
            units_.erase(unit);
    }

    void clearUnits() {
        units_.clear();
    }

    std::shared_ptr<Race> getRace() {
        return race_;
    }

    void setRace(std::shared_ptr<Race> race) {
        race_ = race;
    }

signals:

public slots:

private:
    QString player_name_;
    std::multiset<std::shared_ptr<Unit>, unit_comparator> units_;
    std::shared_ptr<Race> race_;
};

#endif // INCLUDEPLAYER_H
