#include "adcore.h"

AD_Core::AD_Core(QObject *parent) :
    QThread(parent)
{
    step = 0;
    Loader * adloader = new Loader();
    adloader->load("data2.xml");
    addata = adloader->loadlevel(1);
    delete adloader;
    if (addata != 0) qDebug("Success");
    else qFatal("Error");
    adtowers = new Towers(addata);
    adsplashes = new Splashes(addata);
    connect(addata->map,SIGNAL(recreateAlienPath(bool*)),addata->aliens,SLOT(retrace(bool*)));
    connect(adtowers,SIGNAL(shot(TowerType)),adsplashes,SLOT(addSplash(TowerType)));
    connect(adsplashes,SIGNAL(killAlien(int,int)),this,SLOT(killAlien(int,int)));
    waveInProgress = false;
    waveEnd = true;
    timer = startTimer(40);
}


void AD_Core::next()
{
    adtowers->update();
    adsplashes->update();
    addata->aliens->update();
//    foreach(Player * p, addata->players)
//    {
//        if (!addata->aliens->curAliens.contains(p->selectAlienId)) p->selectAlienId = -1;
//    }
    waveProcessing();
    step++;
}


void AD_Core::timerEvent(QTimerEvent * )
{
    next();
}


void AD_Core::nextWave()
{
    if (!waveEnd && waveInProgress)
    {
        qDebug("wave in progress");
        return;
    }
    if (addata->curWave >= addata->waves.size()) {
        qDebug("level finished");
        return;
    }
    //wavetime = addata->waves.at(addata->curWave).timeout;
    wavetime = 0;
    addata->curWave++;
    waveInProgress = true;
    waveEnd = false;
    qDebug() << tr("Next wave %1").arg(addata->curWave+1);
}


void AD_Core::waveProcessing()
{
    /// FIXME : resolve problem with prise for finish wave, it is calculated wrong!
    if (addata->aliens->curAliens.isEmpty() && !waveInProgress && !waveEnd)
    {
        if(addata->curWave > 0) addata->players.at(0)->money += addata->waves.at(addata->curWave-1).prise;
        waveEnd = true;
    }
    if (!waveInProgress) return;
    if (wavetime <= 0) {
        for (int i=0; i<addata->waves.at(addata->curWave).counts.size(); i++) {
            if (addata->waves.at(addata->curWave).counts.at(i) > 0) {
                addata->aliens->addAlien(addata->waves.at(addata->curWave).types.at(i));
                addata->waves[addata->curWave].counts[i]--;
                wavetime = addata->waves.at(addata->curWave).timeout;
                return;
            }
        }
        waveInProgress = false;
    } else {
        wavetime--;
    }
}


void AD_Core::killAlien(int playerId, int alienId)
{
//    qDebug() << playerId << alienId;
    Player * pl = addata->players[playerId];
    pl->money += addata->aliens->curAliens[alienId].src->prise;
    pl->stats.killed_aliens++;
    addata->aliens->delAlien(alienId);
}


void AD_Core::setScene(QGraphicsScene *scene)
{
    addata->aliens->setScene(scene);
    adtowers->setScene(scene);
    adsplashes->setScene(scene);
}


void AD_Core::setSpeed(float x)
{
    killTimer(timer);
    timer = startTimer(qRound(40.f/x));
}
