#include <hotseatgame/unitsqueue.h>
#include <vector>
#include <string>
#include <algorithm>
#include <units/unit.h>

void UnitsQueue::add(Unit* unit){
    queue_.push_back(unit);
    recalcQueue();
}

void UnitsQueue::remove(viterator iter){
    if (beginIterator() <= iter && iter < endIterator()){
        queue_.erase(iter);
        return;
    }
    throw std::string("Iterator is not in UnitsQueue");
}

void UnitsQueue::remove(Unit* unit){
    for (viterator it = beginIterator(); it != endIterator();++it){
        if( (*it) == unit){
            remove(it);
            return;
        }
    }
    throw std::string("Unit* is not in UnitsQueue");
}

UnitsQueue::viterator UnitsQueue::beginIterator() {
    return queue_.begin();
}

UnitsQueue::viterator UnitsQueue::endIterator(){
    return queue_.end();
}

Unit* UnitsQueue::front(){
    return *beginIterator();
}

void UnitsQueue::pop(){
    return remove(beginIterator());
}

void UnitsQueue::recalcQueue(){
    std::stable_sort(beginIterator(), endIterator(),[](Unit* a, Unit* b)->bool{
        auto a_init = a->getInitiative();
        auto b_init = b->getInitiative();
        return a_init > b_init;
    });
}
