#include "mainwindow.h"
#include "ui_mainwindow.h"


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::MainWindow)
{
    qDebug() << "Load START!";
    ui->setupUi(this);
    sndr = new UdpSender("127.0.0.1",10101);
    //sndr->connectSend("hellow");
    cellsize = 16;
    destx = this->width() / cellsize;
    desty = this->height() / cellsize / 2;
    QTimer *timer = new QTimer(this);
    adp = new adpainter(this->width(),this->height(),cellsize);
    adp->clear();
    adp->drawgrid();
    connect(timer, SIGNAL(timeout()), this, SLOT(ADrender()));
    aliens = new Aliens(destx, desty, this->width() / cellsize ,this->height() / cellsize, cellsize);
    if (!aliens->AddAlien()) qDebug() << "Error Loading";
    this->setGeometry(100,100,this->width(),this->height());
    //qDebug() << "QT version" << qVersion();
    //AnimAlien = 0;
    timer->start(50);
    qDebug() << "Load DONE!";
}


void MainWindow::ADrender()
{
    //aliens->AddAlien();
    aliens->updateAliens();
    adp->drawAliens(&aliens->curAliens[0], &aliens->AliensPixmaps[aliens->curAliens[0].PicType]);
    this->repaint();
}


void MainWindow::paintEvent(QPaintEvent*)
{
    QPainter painter;
    painter.begin(this);
    painter.drawPixmap(0,0,*adp->getPixmap());
    painter.end();
}


void MainWindow::mouseMoveEvent ( QMouseEvent * event )
{
    if (mousebt == 1)  ClearCell(event->x(),event->y());
    else SetCell(event->x(),event->y());
}


void MainWindow::mousePressEvent ( QMouseEvent * event )
{
    if (event->button() == Qt::RightButton) {
        ClearCell(event->x(),event->y());
        mousebt = 1;
    } else {
        SetCell(event->x(),event->y());
        mousebt = 0;
    }
}


void MainWindow::SetCell(int x, int y)
{
    QPoint cp;
    QRect wdrect(0, 0, (this->width() / cellsize) * cellsize, (this->height() / cellsize) * cellsize);
    if (wdrect.contains(x,y)) {
        cp.setX((int) x / cellsize);
        cp.setY((int) y / cellsize);
        //qDebug() << "click: " << cp.x() << ";" << cp.y();
        aliens->Cells[cp.x()][cp.y()] = - 1;
        adp->drawcell(cp);
        //aliens->recreatePath();
        adp->StepAlien=0;
        //adp->AnimAlien=0;
        //aliens->curAliens[aliens->CurWave].Position.pnt = aliens->curAliens[aliens->CurWave-1].path[adp->StepAlien];
        if (!aliens->recreatePath()) ClearCell(x,y);
    }
}


void MainWindow::ClearCell(int x, int y)
{
    QPoint cp;
    QRect wdrect(0, 0, (this->width() / cellsize) * cellsize, (this->height() / cellsize) * cellsize);
    if (wdrect.contains(x,y)) {
        cp.setX((int) x / cellsize);
        cp.setY((int) y / cellsize);
        //qDebug() << "click: " << cp.x() << ";" << cp.y();
        aliens->Cells[cp.x()][cp.y()] = 0;
        adp->clearcell(cp);
        adp->StepAlien=0;
        qDebug() << aliens->recreatePath();
        //aliens->clearAliens();
        //aliens->AddAlien();

    }
}


MainWindow::~MainWindow()
{
    delete ui;
	delete aliens;
    delete adp;
}
