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

#include <QMessageBox>
#include <QFileDialog>
#include <QSettings>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->pbSave->setIcon(QIcon::fromTheme("document-save", QIcon(":/icons/icons/document-save.png")));
    ui->pbReload->setIcon(QIcon::fromTheme("edit-undo", QIcon(":/icons/icons/edit-undo.png")));
    ui->pbAlAdd->setIcon(QIcon::fromTheme("list-add", QIcon(":/icons/icons/list-add.png")));
    ui->pbAlDel->setIcon(QIcon::fromTheme("list-remove", QIcon(":/icons/icons/list-remove.png")));
    ui->pbTrigAdd->setIcon(QIcon::fromTheme("list-add", QIcon(":/icons/icons/list-add.png")));
    ui->pbTrigDel->setIcon(QIcon::fromTheme("list-remove", QIcon(":/icons/icons/list-remove.png")));
    ui->pbTwAdd->setIcon(QIcon::fromTheme("list-add", QIcon(":/icons/icons/list-add.png")));
    ui->pbTwDel->setIcon(QIcon::fromTheme("list-remove", QIcon(":/icons/icons/list-remove.png")));
    ui->pbMapAdd->setIcon(QIcon::fromTheme("list-add", QIcon(":/icons/icons/list-add.png")));
    ui->pbMapDelete->setIcon(QIcon::fromTheme("list-remove", QIcon(":/icons/icons/list-remove.png")));
    ui->pbSplAdd->setIcon(QIcon::fromTheme("list-add", QIcon(":/icons/icons/list-add.png")));
    ui->pbSlpDel->setIcon(QIcon::fromTheme("list-remove", QIcon(":/icons/icons/list-remove.png")));
    ui->pbAnimAdd->setIcon(QIcon::fromTheme("list-add", QIcon(":/icons/icons/list-add.png")));
    ui->pbAnimDel->setIcon(QIcon::fromTheme("list-remove", QIcon(":/icons/icons/list-remove.png")));
    ui->pbWaveAdd->setIcon(QIcon::fromTheme("list-add", QIcon(":/icons/icons/list-add.png")));
    ui->pbWaveDel->setIcon(QIcon::fromTheme("list-remove", QIcon(":/icons/icons/list-remove.png")));
    ui->pbImgAdd->setIcon(QIcon::fromTheme("list-add", QIcon(":/icons/icons/list-add.png")));
    ui->pbImgDel->setIcon(QIcon::fromTheme("list-remove", QIcon(":/icons/icons/list-remove.png")));
    ui->pbTwSplashEdit->setIcon(QIcon::fromTheme("edit", QIcon(":/icons/icons/edit.png")));
    ui->pbMapEdit->setIcon(QIcon::fromTheme("edit", QIcon(":/icons/icons/edit.png")));
    adloader = new Loader();
    adloader->load("data2.xml");

    wavePartModel = new WavePartModel(adloader->waves);
    waveModel = new WaveModel(adloader->waves);
//    waveModel->setCurrentWave(0);
    connect(waveModel,SIGNAL(needUpdateIndex()),wavePartModel,SLOT(updateIndex()));
    ui->tableWaves->setModel((QAbstractItemModel * )waveModel);
    ui->tableWaveParts->setModel((QAbstractItemModel * )wavePartModel);
    connect(ui->tableWaves->selectionModel(),SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),wavePartModel,SLOT(setCurrentWave(QModelIndex,QModelIndex)));
    connect(ui->tableWaveParts->selectionModel(),SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),this,SLOT(tbWavePartSelect(QModelIndex,QModelIndex)));

    animModel = new AnimationModel(adloader->animations);
    ui->lvAnimations->setModel((QAbstractItemModel * )animModel);
    connect(ui->lvAnimations->selectionModel(),SIGNAL(currentChanged(QModelIndex,QModelIndex)),this,SLOT(lvAnimations_select(QModelIndex, QModelIndex)));
    ui->lvAnimations->selectionModel()->setCurrentIndex(ui->lvAnimations->model()->index(0,0),QItemSelectionModel::ClearAndSelect);

    mapScene = new QGraphicsScene();
    ui->gvMap->setScene(mapScene);
    ui->gvMap->scale(10,10);

    mapModel = new MapModel(adloader->maps.values());
    ui->lvMaps->setModel((QAbstractItemModel * )mapModel);
    connect(ui->lvMaps->selectionModel(),SIGNAL(currentChanged(QModelIndex, QModelIndex)),this,SLOT(lvMaps_select(QModelIndex, QModelIndex)));
    ui->lvMaps->selectionModel()->setCurrentIndex(ui->lvMaps->model()->index(0,0),QItemSelectionModel::ClearAndSelect);

    alModel = new AlienModel(adloader->aliens.values());
    ui->lvAliens->setModel((QAbstractItemModel * )alModel);
    ui->cbAlImage->setModel((QAbstractItemModel * )animModel);
    ui->lvWaveAliens->setModel((QAbstractItemModel * )alModel);
    connect(ui->lvAliens->selectionModel(),SIGNAL(currentChanged(QModelIndex, QModelIndex)),this,SLOT(lvAliens_select(QModelIndex, QModelIndex)));
    ui->lvAliens->selectionModel()->setCurrentIndex(ui->lvAliens->model()->index(0,0),QItemSelectionModel::ClearAndSelect);

    splModel = new SplashModel(adloader->splashes.values());
    ui->lvSplashes->setModel((QAbstractItemModel * )splModel);
    ui->cbSplImage->setModel((QAbstractItemModel * )animModel);
    connect(ui->lvSplashes->selectionModel(),SIGNAL(currentChanged(QModelIndex, QModelIndex)),this,SLOT(lvSplashes_select(QModelIndex, QModelIndex)));
    ui->lvSplashes->selectionModel()->setCurrentIndex(ui->lvSplashes->model()->index(0,0),QItemSelectionModel::ClearAndSelect);

    twModel = new TowerModel(adloader->towers.values());
    ui->lvTowers->setModel((QAbstractItemModel * )twModel);
    ui->cbTwSplash->setModel((QAbstractItemModel * )splModel);
    ui->cbTwImage->setModel((QAbstractItemModel * )animModel);
    connect(ui->lvTowers->selectionModel(),SIGNAL(currentChanged(QModelIndex, QModelIndex)),this,SLOT(lvTowers_select(QModelIndex, QModelIndex)));
    ui->lvTowers->selectionModel()->setCurrentIndex(ui->lvTowers->model()->index(0,0),QItemSelectionModel::ClearAndSelect);

    trigModel = new TriggerModel(adloader->triggers.values());
    ui->lvTriggers->setModel((QAbstractItemModel * )trigModel);
    connect(ui->lvTriggers->selectionModel(),SIGNAL(currentChanged(QModelIndex, QModelIndex)),this,SLOT(lvTriggers_select(QModelIndex,QModelIndex)));
    ui->lvTriggers->selectionModel()->setCurrentIndex(ui->lvTriggers->model()->index(0,0),QItemSelectionModel::ClearAndSelect);
    ui->cbTrigChildAim->addItem(tr("no aim"),QVariant(srcTriggerType::noAim));
    ui->cbTrigChildAim->addItem(tr("random side"),QVariant(srcTriggerType::allSide));
    ui->cbTrigChildAim->addItem(tr("parent aim"),QVariant(srcTriggerType::parentAim));
    ui->cbTrigChildAim->addItem(tr("nearest alien"),QVariant(srcTriggerType::nearestAlien));
    ui->cbTrigType->addItem(tr("on destination"),QVariant(srcTriggerType::onDestination));
    ui->cbTrigType->addItem(tr("on alien in radius"),QVariant(srcTriggerType::onAlienInRadius));
    ui->cbTrigType->addItem(tr("on timer"),QVariant(srcTriggerType::onTimer));
    isSaved = true;
    QSettings sett("Alien_Defender","aliendefender");
    this->restoreGeometry(sett.value("session/geometry").toByteArray());
    this->restoreState(sett.value("session/mainwindow").toByteArray());
    ui->splitter->restoreState(sett.value("session/split1").toByteArray());
    ui->splitter_2->restoreState(sett.value("session/split2").toByteArray());
    ui->splitter_3->restoreState(sett.value("session/split3").toByteArray());
    ui->splitter_4->restoreState(sett.value("session/split4").toByteArray());
    ui->splitter_5->restoreState(sett.value("session/split5").toByteArray());
    ui->splitter_6->restoreState(sett.value("session/split6").toByteArray());
    ui->tabWidget->setCurrentIndex(sett.value("session/tab").toInt());
    //alb = new AnimLabel();
    //ui->verticalLayout->addWidget(alb);
    //alb->setAnimation(adloader->animations.value(1).pathes);
}


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


void MainWindow::changeEvent(QEvent *e)
{
    QMainWindow::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}


void MainWindow::on_cbAlArmor_toggled(bool checked)
{
    int id = adloader->aliens.values().at(ui->lvAliens->currentIndex().row()).id;
    float lval = adloader->aliens[id].armor;
    ui->sbAlArmor->setEnabled(checked);
    if (checked) adloader->aliens[id].armor = ui->sbAlArmor->value();
    else adloader->aliens[id].armor = 0;
    if (lval != adloader->aliens[id].armor) isSaved = false;
}


void MainWindow::on_cbAlRegeneration_toggled(bool checked)
{
    int id = adloader->aliens.values().at(ui->lvAliens->currentIndex().row()).id;
    float lval = adloader->aliens[id].regeneration;
    ui->sbAlregeneration->setEnabled(checked);
    if (checked) adloader->aliens[id].regeneration = ui->sbAlregeneration->value();
    else adloader->aliens[id].regeneration = 0;
    if (lval != adloader->aliens[id].regeneration) isSaved = false;
}


void MainWindow::lvAnimations_select(QModelIndex index, QModelIndex)
{
    if (index.isValid())
    {
        ui->lwImages->clear();
        refresh_lwImages(adloader->animations.values().at(index.row()).pathes);
    }
}


void MainWindow::lvAliens_select(QModelIndex index, QModelIndex)
{
    if (index.isValid())
    {
        tbAlien al = adloader->aliens.values().at(index.row());
        ui->leAlName->setText(al.name);
        ui->sbAlHealth->setValue(al.health);
        ui->sbAlArmor->setValue(al.armor);
        if (al.armor > 0) ui->cbAlArmor->setChecked(true);
        else ui->cbAlArmor->setChecked(false);
        ui->sbAlSpeed->setValue(al.speed);
        ui->sbAlPrise->setValue(al.prise);
        ui->sbAlregeneration->setValue(al.regeneration);
        if (al.regeneration > 0) ui->cbAlRegeneration->setChecked(true);
        else ui->cbAlRegeneration->setChecked(false);
        ui->sbAlScore->setValue(al.score);
        ui->cbAlIsFly->setChecked(al.isFlying);
        ui->cbAlImage->setCurrentIndex(adloader->animations.keys().indexOf(al.imgType));
        ui->lbAlAnim->setAnimation(adloader->animations.value(al.imgType).pathes);
    }
}


void MainWindow::lvMaps_select(QModelIndex index, QModelIndex)
{
    if (index.isValid())
    {
        tbMap map = adloader->maps.values().at(index.row());
        ui->leMapName->setText(map.name);
        ui->sbMapHei->setValue(map.size.height());
        ui->sbMapWid->setValue(map.size.width());
        ui->sbMapPlayers->setValue(map.maxPlayers);
        Map m(map.data,map.size,map.name,map.maxPlayers,map.imgType);
        QPixmap pix(map.size);
        QPainter p(&pix);
        p.fillRect(m.rect(),Qt::white);
        for (int i=0; i<m.cells().size(); i++) {
            for (int j=0; j<m.cells().at(i).size(); j++) {
                QPen pen;
                pen.setColor(Qt::white);
                int cel = m.cells().at(i).at(j);
                if (cel == Map::Wall)
                    pen.setColor(Qt::black);
                if (cel >= Map::Free || (cel <= Map::PlayerTower && cel !=Map::Wall))
                    pen.setColor(QColor(qAbs(cel+2)*345%255,(qAbs(cel+2)*721)%255,(qAbs(cel+2)*75)%255,200));
                p.setPen(pen);
                p.drawPoint(i,j);
            }
        }
        p.end();
        mapScene->clear();
        mapScene->addPixmap(pix);
        ui->gvMap->centerOn(0,0);
        //ui->gvMap->resetCachedContent();
        //ui->pbMapEdit->setIcon(QIcon(pix));
    }
}


void MainWindow::lvTowers_select(QModelIndex index, QModelIndex)
{
    if (index.isValid())
    {
        tbTower tw = adloader->towers.values().at(index.row());
        ui->sbTwBuildTime->setValue(tw.buildTime);
        ui->sbTwCost->setValue(tw.cost);
        ui->sbTwExpByDam->setValue(tw.expByDamage);
        if (tw.expByDamage > 0)
            ui->cbTwExpByDam->setChecked(true);
        else
            ui->cbTwExpByDam->setChecked(false);
        ui->sbTwExpByKill->setValue(tw.expByKill);
        if (tw.expByKill > 0)
            ui->cbTwExpByKill->setChecked(true);
        else
            ui->cbTwExpByKill->setChecked(false);
        ui->sbTwExpByShot->setValue(tw.expByShot);
        if (tw.expByShot > 0)
            ui->cbTwExpByShot->setChecked(true);
        else
            ui->cbTwExpByShot->setChecked(false);
        ui->leTwName->setText(tw.name);
        ui->sbTwRadius->setValue(tw.radius);
        ui->sbTwReload->setValue(tw.reload);
        ui->cbTwSplash->setCurrentIndex(adloader->splashes.keys().indexOf(tw.splashId));
        ui->cbTwImage->setCurrentIndex(adloader->animations.keys().indexOf(tw.imgType));
        ui->lbTwAnim->setAnimation(adloader->animations.value(tw.imgType).pathes);
    }
}


void MainWindow::lvSplashes_select(QModelIndex index, QModelIndex)
{
    if (index.isValid())
    {
        tbSplash spl = adloader->splashes.values().at(index.row());
        ui->sbSplLifeTime->setValue(spl.lifetime);
        ui->sbSplSpeed->setValue(spl.speed);
        ui->cbSplAutoControl->setChecked(spl.autoControl);
        ui->cbSplKeepOnAlien->setChecked(spl.keepOnAlien);
        ui->leSplName->setText(spl.name);
        ui->cbSplImage->setCurrentIndex(adloader->animations.keys().indexOf(spl.imgType));
        ui->lbSplAnim->setAnimation(adloader->animations.value(spl.imgType).pathes);
        ui->sbSplZValue->setValue(spl.ZValue);
        switch (spl.compositionMode)
        {
        case QPainter::RasterOp_NotSource :
            ui->cbSplCompisitionMode->setCurrentIndex(1);
            break;
        case QPainter::CompositionMode_Plus :
            ui->cbSplCompisitionMode->setCurrentIndex(2);
            break;
        case QPainter::CompositionMode_Multiply :
            ui->cbSplCompisitionMode->setCurrentIndex(3);
            break;
        case QPainter::CompositionMode_Screen :
            ui->cbSplCompisitionMode->setCurrentIndex(4);
            break;
        case QPainter::CompositionMode_Darken :
            ui->cbSplCompisitionMode->setCurrentIndex(5);
            break;
        case QPainter::CompositionMode_Lighten :
            ui->cbSplCompisitionMode->setCurrentIndex(6);
            break;
        case QPainter::CompositionMode_ColorDodge :
            ui->cbSplCompisitionMode->setCurrentIndex(7);
            break;
        case QPainter::CompositionMode_ColorBurn :
            ui->cbSplCompisitionMode->setCurrentIndex(8);
            break;
        case QPainter::CompositionMode_HardLight :
            ui->cbSplCompisitionMode->setCurrentIndex(9);
            break;
        case QPainter::CompositionMode_SoftLight :
            ui->cbSplCompisitionMode->setCurrentIndex(10);
            break;
        case QPainter::CompositionMode_Difference :
            ui->cbSplCompisitionMode->setCurrentIndex(11);
            break;
        case QPainter::CompositionMode_SourceOver :
        default:
            ui->cbSplCompisitionMode->setCurrentIndex(0);
            break;
        }
    }
}


void MainWindow::lvTriggers_select(QModelIndex index, QModelIndex)
{
    if (index.isValid())
    {
        tbTrigger trig = adloader->triggers.values().at(index.row());
        ui->sbTrigCount->setValue(trig.count);
        if (trig.count > 0)
            ui->cbTrigCount->setChecked(true);
        else
            ui->cbTrigCount->setChecked(false);
        ui->sbTrigDamage->setValue(trig.damage);
        if (trig.damage > 0)
            ui->cbTrigDamage->setChecked(true);
        else
            ui->cbTrigDamage->setChecked(false);
        ui->sbTrigDamRadius->setValue(trig.radius);
        if (trig.radius > 0)
            ui->cbTrigDamRad->setChecked(true);
        else
            ui->cbTrigDamRad->setChecked(false);
        ui->sbTrigChance->setValue(trig.chance);
        if (trig.chance == 100)
            ui->cbTrigChance->setChecked(false);
        else
            ui->cbTrigChance->setChecked(true);
        ui->sbTrigRandomRadius->setValue(trig.randomPosRadius);
        if (trig.randomPosRadius > 0)
            ui->cbTrigRandRadius->setChecked(true);
        else
            ui->cbTrigRandRadius->setChecked(false);

        ui->sbTrigTimer->setValue(trig.timer);
        switch (trig.type)
        {
        case srcTriggerType::onDestination :
            ui->cbTrigType->setCurrentIndex(0);
            break;
        case srcTriggerType::onAlienInRadius :
            ui->cbTrigType->setCurrentIndex(1);
            break;
        case srcTriggerType::onTimer :
            ui->cbTrigType->setCurrentIndex(2);
            break;
        }
        if (trig.type != srcTriggerType::onTimer)
        {
            ui->lbTrigTimer->setVisible(false);
            ui->sbTrigTimer->setVisible(false);
        } else {
            ui->lbTrigTimer->setVisible(true);
            ui->sbTrigTimer->setVisible(true);
        }
        switch (trig.childAim)
        {
        case srcTriggerType::noAim :
            ui->cbTrigChildAim->setCurrentIndex(0);
            break;
        case srcTriggerType::allSide :
            ui->cbTrigChildAim->setCurrentIndex(1);
            break;
        case srcTriggerType::parentAim :
            ui->cbTrigChildAim->setCurrentIndex(2);
            break;
        case srcTriggerType::nearestAlien :
            ui->cbTrigChildAim->setCurrentIndex(3);
            break;
        }
        ui->leTrigName->setText(trig.name);
    }
}


void MainWindow::closeEvent(QCloseEvent *event)
{
    QSettings sett("Alien_Defender","aliendefender");
    sett.setValue("session/geometry",this->saveGeometry());
    sett.setValue("session/mainwindow",this->saveState());
    sett.setValue("session/split1",ui->splitter->saveState());
    sett.setValue("session/split2",ui->splitter_2->saveState());
    sett.setValue("session/split3",ui->splitter_3->saveState());
    sett.setValue("session/split4",ui->splitter_4->saveState());
    sett.setValue("session/split5",ui->splitter_5->saveState());
    sett.setValue("session/split6",ui->splitter_6->saveState());
    sett.setValue("session/tab",ui->tabWidget->currentIndex());
    if (!isSaved)
    {
        QMessageBox msgBox;
        msgBox.setText(tr("Save changes?"));
        msgBox.setStandardButtons(QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel);
        msgBox.setDefaultButton(QMessageBox::Save);
        msgBox.setEscapeButton(QMessageBox::Discard);
        int ret = msgBox.exec();
        switch (ret)
        {
        case QMessageBox::Save :
            adloader->save("data2.xml");
            adloader->load("data2.xml");
            adloader->save("data2.xml");
            event->accept();
            break;
        case QMessageBox::Cancel :
            event->ignore();
            break;
        }
    } else {
        event->accept();
    }
}

void MainWindow::on_pbSave_clicked()
{
    adloader->save("data2.xml");
    adloader->load("data2.xml");
    adloader->save("data2.xml");
    isSaved = true;
}


void MainWindow::on_pbReload_clicked()
{
    QMessageBox msgBox;
    msgBox.setText(tr("All unsaved changes will be lost"));
    msgBox.setInformativeText(tr("Are you sure?"));
    msgBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel);
    msgBox.setDefaultButton(QMessageBox::Ok);
    int ret = msgBox.exec();
    if (ret == QMessageBox::Ok)
    {
        adloader->load("data2.xml");
        alModel->refresh(adloader->aliens.values());
        twModel->refresh(adloader->towers.values());
        splModel->refresh(adloader->splashes.values());
        trigModel->refresh(adloader->triggers.values());
        //        animModel->refresh(adloader->animations.values());
        mapModel->refresh(adloader->maps.values());
        ui->lvAnimations->reset();
        ui->lvAnimations->selectionModel()->setCurrentIndex(ui->lvAnimations->model()->index(0,0),QItemSelectionModel::ClearAndSelect);
        ui->lvMaps->reset();
        ui->lvMaps->selectionModel()->setCurrentIndex(ui->lvMaps->model()->index(0,0),QItemSelectionModel::ClearAndSelect);
        ui->lvAliens->reset();
        ui->lvAliens->selectionModel()->setCurrentIndex(ui->lvAliens->model()->index(0,0),QItemSelectionModel::ClearAndSelect);
        ui->lvSplashes->reset();
        ui->lvSplashes->selectionModel()->setCurrentIndex(ui->lvSplashes->model()->index(0,0),QItemSelectionModel::ClearAndSelect);
        ui->lvTowers->reset();
        ui->lvTowers->selectionModel()->setCurrentIndex(ui->lvTowers->model()->index(0,0),QItemSelectionModel::ClearAndSelect);
        ui->lvTriggers->reset();
        ui->lvTriggers->selectionModel()->setCurrentIndex(ui->lvTriggers->model()->index(0,0),QItemSelectionModel::ClearAndSelect);
        isSaved = true;
    }
}


void MainWindow::on_sbAlHealth_valueChanged(double value)
{
    int id = adloader->aliens.values().at(ui->lvAliens->currentIndex().row()).id;
    float lval = adloader->aliens[id].health;
    adloader->aliens[id].health = value;
    if (lval != adloader->aliens[id].health) isSaved = false;
}


void MainWindow::on_sbAlArmor_valueChanged(double value)
{
    int id = adloader->aliens.values().at(ui->lvAliens->currentIndex().row()).id;
    float lval = adloader->aliens[id].armor;
    adloader->aliens[id].armor = value;
    if (lval != adloader->aliens[id].armor) isSaved = false;
}


void MainWindow::on_sbAlregeneration_valueChanged(double value)
{
    int id = adloader->aliens.values().at(ui->lvAliens->currentIndex().row()).id;
    float lval = adloader->aliens[id].regeneration;
    adloader->aliens[id].regeneration = value;
    if (lval != adloader->aliens[id].regeneration) isSaved = false;
}


void MainWindow::on_sbAlSpeed_valueChanged(double value)
{
    int id = adloader->aliens.values().at(ui->lvAliens->currentIndex().row()).id;
    float lval = adloader->aliens[id].speed;
    adloader->aliens[id].speed = value;
    if (lval != adloader->aliens[id].speed) isSaved = false;
}


void MainWindow::on_sbAlPrise_valueChanged(int val)
{
    int id = adloader->aliens.values().at(ui->lvAliens->currentIndex().row()).id;
    unsigned int lval = adloader->aliens[id].prise;
    adloader->aliens[id].prise = val;
    if (lval != adloader->aliens[id].prise) isSaved = false;
}


void MainWindow::on_sbAlScore_valueChanged(int val)
{
    int id = adloader->aliens.values().at(ui->lvAliens->currentIndex().row()).id;
    unsigned int lval = adloader->aliens[id].score;
    adloader->aliens[id].score = val;
    if (lval != adloader->aliens[id].score) isSaved = false;
}


void MainWindow::on_cbAlIsFly_toggled(bool checked)
{
    int id = adloader->aliens.values().at(ui->lvAliens->currentIndex().row()).id;
    bool lval = adloader->aliens[id].isFlying;
    adloader->aliens[id].isFlying = checked;
    if (lval != adloader->aliens[id].isFlying) isSaved = false;
}


void MainWindow::on_leAlName_editingFinished()
{
    int id = adloader->aliens.values().at(ui->lvAliens->currentIndex().row()).id;
    QString lval = adloader->aliens[id].name;
    adloader->aliens[id].name = ui->leAlName->text();
    alModel->refresh(adloader->aliens.values());
    QModelIndex mindex = ui->lvAliens->currentIndex();
    ui->lvAliens->reset();
    ui->lvAliens->setCurrentIndex(mindex);
    if (lval != adloader->aliens[id].name) isSaved = false;
}


void MainWindow::on_pbAlAdd_clicked()
{
    int i = 1;
    while (adloader->aliens.contains(i)) i++;
    tbAlien al;
    al.id = i;
    al.name = tr("Alien");
    al.health = 1;
    al.prise = 0;
    al.score = 1;
    al.speed = 1;
    adloader->aliens.insert(al.id,al);
    int index = adloader->aliens.keys().indexOf(i);
    alModel->refresh(adloader->aliens.values());
    ui->lvAliens->reset();
    ui->lvAliens->selectionModel()->setCurrentIndex(ui->lvAliens->model()->index(index,0),QItemSelectionModel::ClearAndSelect);
    isSaved = false;
}


void MainWindow::on_pbAlDel_clicked()
{
    if (adloader->aliens.size() < 2) return;
    QMessageBox msgBox;
    int id = adloader->aliens.keys().at(ui->lvAliens->currentIndex().row());
    for (int i=0; i<adloader->waves.size(); i++)
    {
        for (int j=0; j<adloader->waves[i].parts.size(); j++)
        {
            if (adloader->waves[i].parts[j].alienId == id)
            {
                msgBox.setText(tr("You can not delete alien %1 id=%2").arg(adloader->aliens.value(id).name).arg(id));
                msgBox.setInformativeText(tr("It used in wawe %1").arg(adloader->waves[i].id));
                msgBox.setStandardButtons(QMessageBox::Ok);
                msgBox.exec();
                return;
            }
        }
    }
    msgBox.setText(tr("Delete alien %1 id=%2").arg(adloader->aliens.value(id).name).arg(id));
    msgBox.setInformativeText(tr("Are you sure?"));
    msgBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel);
    msgBox.setDefaultButton(QMessageBox::Ok);
    int ret = msgBox.exec();
    if (ret == QMessageBox::Ok)
    {
        adloader->aliens.remove(id);
        alModel->refresh(adloader->aliens.values());
        ui->lvAliens->reset();
        ui->lvAliens->selectionModel()->setCurrentIndex(ui->lvAliens->model()->index(0,0),QItemSelectionModel::ClearAndSelect);
        isSaved = false;
    }
}


void MainWindow::on_leTwName_editingFinished()
{
    int id = adloader->towers.values().at(ui->lvTowers->currentIndex().row()).id;
    QString lval = adloader->towers[id].name;
    adloader->towers[id].name = ui->leTwName->text();
    twModel->refresh(adloader->towers.values());
    QModelIndex mindex = ui->lvTowers->currentIndex();
    ui->lvTowers->reset();
    ui->lvTowers->setCurrentIndex(mindex);
    if (lval != adloader->towers[id].name) isSaved = false;
}


void MainWindow::on_sbTwBuildTime_valueChanged(int val)
{
    int id = adloader->towers.values().at(ui->lvTowers->currentIndex().row()).id;
    unsigned int lval = adloader->towers[id].buildTime;
    adloader->towers[id].buildTime = val;
    if (lval != adloader->towers[id].buildTime) isSaved = false;
}


void MainWindow::on_sbTwCost_valueChanged(int val)
{
    int id = adloader->towers.values().at(ui->lvTowers->currentIndex().row()).id;
    unsigned int lval = adloader->towers[id].cost;
    adloader->towers[id].cost = val;
    if (lval != adloader->towers[id].cost) isSaved = false;
}


void MainWindow::on_cbTwSplash_currentIndexChanged(int index)
{
    if (!ui->lvTowers->currentIndex().isValid()) return;
    if (index >= 0)
    {
        int id = adloader->towers.values().at(ui->lvTowers->currentIndex().row()).id;
        int lval = adloader->towers[id].splashId;
        adloader->towers[id].splashId = adloader->splashes.values().at(index).id;
        if (lval != adloader->towers[id].splashId) isSaved = false;
    }
}

void MainWindow::on_sbTwReload_valueChanged(int val)
{
    int id = adloader->towers.values().at(ui->lvTowers->currentIndex().row()).id;
    unsigned int lval = adloader->towers[id].reload;
    adloader->towers[id].reload = val;
    if (lval != adloader->towers[id].reload) isSaved = false;
}


void MainWindow::on_sbTwRadius_valueChanged(double val)
{
    int id = adloader->towers.values().at(ui->lvTowers->currentIndex().row()).id;
    float lval = adloader->towers[id].radius;
    adloader->towers[id].radius = val;
    if (lval != adloader->towers[id].radius) isSaved = false;
}


void MainWindow::on_sbTwExpByShot_valueChanged(double val)
{
    int id = adloader->towers.values().at(ui->lvTowers->currentIndex().row()).id;
    float lval = adloader->towers[id].expByShot;
    adloader->towers[id].expByShot = val;
    if (lval != adloader->towers[id].expByShot) isSaved = false;
}


void MainWindow::on_cbTwExpByShot_toggled(bool checked)
{
    int id = adloader->towers.values().at(ui->lvTowers->currentIndex().row()).id;
    float lval = adloader->towers[id].expByShot;
    ui->sbTwExpByShot->setEnabled(checked);
    if (checked) adloader->towers[id].expByShot = ui->sbTwExpByShot->value();
    else adloader->towers[id].expByShot = 0;
    if (lval != adloader->towers[id].expByShot) isSaved = false;
}


void MainWindow::on_sbTwExpByDam_valueChanged(double val)
{
    int id = adloader->towers.values().at(ui->lvTowers->currentIndex().row()).id;
    float lval = adloader->towers[id].expByDamage;
    adloader->towers[id].expByDamage = val;
    if (lval != adloader->towers[id].expByDamage) isSaved = false;
}


void MainWindow::on_cbTwExpByDam_toggled(bool checked)
{
    int id = adloader->towers.values().at(ui->lvTowers->currentIndex().row()).id;
    float lval = adloader->towers[id].expByDamage;
    ui->sbTwExpByDam->setEnabled(checked);
    if (checked) adloader->towers[id].expByDamage = ui->sbTwExpByDam->value();
    else adloader->towers[id].expByDamage = 0;
    if (lval != adloader->towers[id].expByDamage) isSaved = false;
}


void MainWindow::on_sbTwExpByKill_valueChanged(double val)
{
    int id = adloader->towers.values().at(ui->lvTowers->currentIndex().row()).id;
    float lval = adloader->towers[id].expByKill;
    adloader->towers[id].expByKill = val;
    if (lval != adloader->towers[id].expByKill) isSaved = false;
}


void MainWindow::on_cbTwExpByKill_toggled(bool checked)
{
    int id = adloader->towers.values().at(ui->lvTowers->currentIndex().row()).id;
    float lval = adloader->towers[id].expByKill;
    ui->sbTwExpByKill->setEnabled(checked);
    if (checked) adloader->towers[id].expByKill = ui->sbTwExpByKill->value();
    else adloader->towers[id].expByKill = 0;
    if (lval != adloader->towers[id].expByKill) isSaved = false;
}


void MainWindow::on_pbTwAdd_clicked()
{
    int i = 1;
    while (adloader->towers.contains(i)) i++;
    tbTower tw;
    tw.id = i;
    tw.name = tr("Tower");
    tw.splashId = adloader->splashes.keys().at(0);
    tw.buildTime = 1;
    tw.cost = 1;
    tw.radius = 1;
    tw.reload = 1;
    adloader->towers.insert(tw.id,tw);
    int index = adloader->towers.keys().indexOf(i);
    twModel->refresh(adloader->towers.values());
    ui->lvTowers->reset();
    ui->lvTowers->selectionModel()->setCurrentIndex(ui->lvTowers->model()->index(index,0),QItemSelectionModel::ClearAndSelect);
    isSaved = false;
}


void MainWindow::on_pbTwDel_clicked()
{
    if (adloader->towers.size() < 2) return;
    QMessageBox msgBox;
    int id = adloader->towers.keys().at(ui->lvTowers->currentIndex().row());
    for (int i=0; i<adloader->levTowers.size(); i++)
    {
        if (adloader->levTowers.values().at(i).towerId == id)
        {
            msgBox.setText(tr("You can not delete tower %1 id=%2").arg(adloader->towers.value(id).name).arg(id));
            msgBox.setInformativeText(tr("It used in level %1").arg(adloader->levTowers.values().at(i).levelId));
            msgBox.setStandardButtons(QMessageBox::Ok);
            msgBox.exec();
            return;
        }
    }
    msgBox.setText(tr("Delete tower %1 id=%2").arg(adloader->towers.value(id).name).arg(id));
    msgBox.setInformativeText(tr("Are you sure?"));
    msgBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel);
    msgBox.setDefaultButton(QMessageBox::Ok);
    int ret = msgBox.exec();
    if (ret == QMessageBox::Ok)
    {
        adloader->towers.remove(id);
        twModel->refresh(adloader->towers.values());
        ui->lvTowers->reset();
        ui->lvTowers->selectionModel()->setCurrentIndex(ui->lvTowers->model()->index(0,0),QItemSelectionModel::ClearAndSelect);
        isSaved = false;
    }
}

void MainWindow::on_leSplName_editingFinished()
{
    int id = adloader->splashes.values().at(ui->lvSplashes->currentIndex().row()).id;
    QString lval = adloader->splashes[id].name;
    adloader->splashes[id].name = ui->leSplName->text();
    splModel->refresh(adloader->splashes.values());
    //ui->lvSplashes->setModel((QAbstractItemModel * )splModel);
    //ui->cbTwSplash->setModel((QAbstractItemModel * )splModel);
    QModelIndex mindex = ui->lvSplashes->currentIndex();
    ui->lvSplashes->reset();
    ui->lvSplashes->setCurrentIndex(mindex);
    if (lval != adloader->splashes[id].name) isSaved = false;
}


void MainWindow::on_sbSplSpeed_valueChanged(double val)
{
    int id = adloader->splashes.values().at(ui->lvSplashes->currentIndex().row()).id;
    float lval = adloader->splashes[id].speed;
    adloader->splashes[id].speed = val;
    if (lval != adloader->splashes[id].speed) isSaved = false;
}


void MainWindow::on_cbSplAutoControl_toggled(bool checked)
{
    int id = adloader->splashes.values().at(ui->lvSplashes->currentIndex().row()).id;
    bool lval = adloader->splashes[id].autoControl;
    adloader->splashes[id].autoControl = checked;
    if (lval != adloader->splashes[id].autoControl) isSaved = false;
}


void MainWindow::on_sbSplLifeTime_valueChanged(int val)
{
    int id = adloader->splashes.values().at(ui->lvSplashes->currentIndex().row()).id;
    unsigned int lval = adloader->splashes[id].lifetime;
    adloader->splashes[id].lifetime = val;
    if (lval != adloader->splashes[id].lifetime) isSaved = false;
}


void MainWindow::on_pbSplAdd_clicked()
{
    int i = 1;
    while (adloader->splashes.contains(i)) i++;
    tbSplash spl;
    spl.id = i;
    spl.name = tr("Splash");
    spl.lifetime = 1;
    spl.speed = 1;
    adloader->splashes.insert(spl.id,spl);
    int index = adloader->splashes.keys().indexOf(i);
    splModel->refresh(adloader->splashes.values());
    ui->lvSplashes->reset();
    ui->lvSplashes->selectionModel()->setCurrentIndex(ui->lvSplashes->model()->index(index,0),QItemSelectionModel::ClearAndSelect);
    isSaved = false;
}



void MainWindow::on_pbSlpDel_clicked()
{
    if (adloader->splashes.size() < 2) return;
    QMessageBox msgBox;
    int id = adloader->splashes.keys().at(ui->lvSplashes->currentIndex().row());
    for (int i=0; i<adloader->towers.size(); i++)
    {
        if (adloader->towers.values().at(i).splashId == id)
        {
            msgBox.setText(tr("You can not delete splash %1 id=%2").arg(adloader->splashes.value(id).name).arg(id));
            msgBox.setInformativeText(tr("It used by tower %1 id=%2").arg(adloader->towers.values().at(i).name).arg(adloader->towers.values().at(i).id));
            msgBox.setStandardButtons(QMessageBox::Ok);
            msgBox.exec();
            return;
        }
    }
    for (int i=0; i<adloader->chains.size(); i++)
    {
        if (adloader->chains.values().at(i).childSplashId == id
                || adloader->chains.values().at(i).parentSplashId == id)
        {
            msgBox.setText(tr("You can not delete splash %1 id=%2").arg(adloader->splashes.value(id).name).arg(id));
            msgBox.setInformativeText(tr("It used by chain in tower %1 id=%2").arg(adloader->towers.value(adloader->chains.values().at(i).towerId).name).arg(adloader->chains.values().at(i).towerId));
            msgBox.setStandardButtons(QMessageBox::Ok);
            msgBox.exec();
            return;
        }
    }
    msgBox.setText(tr("Delete splash %1 id=%2").arg(adloader->splashes.value(id).name).arg(id));
    msgBox.setInformativeText(tr("Are you sure?"));
    msgBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel);
    msgBox.setDefaultButton(QMessageBox::Ok);
    int ret = msgBox.exec();
    if (ret == QMessageBox::Ok)
    {
        adloader->splashes.remove(id);
        splModel->refresh(adloader->splashes.values());
        ui->lvSplashes->reset();
        ui->lvSplashes->selectionModel()->setCurrentIndex(ui->lvSplashes->model()->index(0,0),QItemSelectionModel::ClearAndSelect);
        isSaved = false;
    }
}


void MainWindow::on_pbTwSplashEdit_clicked()
{
    int splIndex = adloader->splashes.keys().indexOf(adloader->towers.values().at(ui->lvTowers->currentIndex().row()).splashId);
    ui->lvSplashes->selectionModel()->setCurrentIndex(ui->lvSplashes->model()->index(splIndex,0),QItemSelectionModel::ClearAndSelect);
    ui->tabWidget->setCurrentWidget(ui->tabSplashes);
}


void MainWindow::on_cbTrigChance_toggled(bool checked)
{
    int id = adloader->triggers.values().at(ui->lvTriggers->currentIndex().row()).id;
    int lval = adloader->triggers[id].chance;
    ui->sbTrigChance->setEnabled(checked);
    if (checked) adloader->triggers[id].chance = ui->sbTrigChance->value();
    else adloader->triggers[id].chance = 100;
    if (lval != adloader->triggers[id].chance) isSaved = false;
}


void MainWindow::on_sbTrigChance_valueChanged(int val)
{
    int id = adloader->triggers.values().at(ui->lvTriggers->currentIndex().row()).id;
    int lval = adloader->triggers[id].chance;
    adloader->triggers[id].chance = val;
    if (lval != adloader->triggers[id].chance) isSaved = false;
}


void MainWindow::on_leTrigName_editingFinished()
{
    int id = adloader->triggers.values().at(ui->lvTriggers->currentIndex().row()).id;
    QString lval = adloader->triggers[id].name;
    adloader->triggers[id].name = ui->leTrigName->text();
    trigModel->refresh(adloader->triggers.values());
    QModelIndex mindex = ui->lvTriggers->currentIndex();
    ui->lvTriggers->reset();
    ui->lvTriggers->setCurrentIndex(mindex);
    if (lval != adloader->triggers[id].name) isSaved = false;
}


void MainWindow::on_sbTrigCount_valueChanged(int val)
{
    int id = adloader->triggers.values().at(ui->lvTriggers->currentIndex().row()).id;
    int lval = adloader->triggers[id].count;
    adloader->triggers[id].count = val;
    if (lval != adloader->triggers[id].count) isSaved = false;
}


void MainWindow::on_sbTrigRandomRadius_valueChanged(double value)
{
    int id = adloader->triggers.values().at(ui->lvTriggers->currentIndex().row()).id;
    float lval = adloader->triggers[id].randomPosRadius;
    adloader->triggers[id].randomPosRadius = value;
    if (lval != adloader->triggers[id].randomPosRadius) isSaved = false;
}


void MainWindow::on_cbTrigDelPar_toggled(bool checked)
{
    int id = adloader->triggers.values().at(ui->lvTriggers->currentIndex().row()).id;
    bool lval = adloader->triggers[id].delParent;
    adloader->triggers[id].delParent = checked;
    if (lval != adloader->triggers[id].delParent) isSaved = false;
}


void MainWindow::on_sbTrigTimer_valueChanged(int val)
{
    int id = adloader->triggers.values().at(ui->lvTriggers->currentIndex().row()).id;
    unsigned int lval = adloader->triggers[id].timer;
    adloader->triggers[id].timer = val;
    if (lval != adloader->triggers[id].timer) isSaved = false;
}


void MainWindow::on_sbTrigDamage_valueChanged(double value)
{
    int id = adloader->triggers.values().at(ui->lvTriggers->currentIndex().row()).id;
    float lval = adloader->triggers[id].damage;
    adloader->triggers[id].damage = value;
    if (lval != adloader->triggers[id].damage) isSaved = false;
}


void MainWindow::on_sbTrigDamRadius_valueChanged(double value)
{
    int id = adloader->triggers.values().at(ui->lvTriggers->currentIndex().row()).id;
    float lval = adloader->triggers[id].radius;
    adloader->triggers[id].radius = value;
    if (lval != adloader->triggers[id].radius) isSaved = false;
}


void MainWindow::on_cbTrigDamRad_toggled(bool checked)
{
    int id = adloader->triggers.values().at(ui->lvTriggers->currentIndex().row()).id;
    float lval = adloader->triggers[id].radius;
    ui->sbTrigDamRadius->setEnabled(checked);
    if (checked) adloader->triggers[id].radius = ui->sbTrigDamRadius->value();
    else adloader->triggers[id].radius = 0;
    if (lval != adloader->triggers[id].radius) isSaved = false;
}


void MainWindow::on_cbTrigDamage_toggled(bool checked)
{
    int id = adloader->triggers.values().at(ui->lvTriggers->currentIndex().row()).id;
    float lval = adloader->triggers[id].damage;
    ui->sbTrigDamage->setEnabled(checked);
    if (checked) adloader->triggers[id].damage = ui->sbTrigDamage->value();
    else adloader->triggers[id].damage = 0;
    if (lval != adloader->triggers[id].damage) isSaved = false;
}


void MainWindow::on_cbTrigRandRadius_toggled(bool checked)
{
    int id = adloader->triggers.values().at(ui->lvTriggers->currentIndex().row()).id;
    float lval = adloader->triggers[id].randomPosRadius;
    ui->sbTrigRandomRadius->setEnabled(checked);
    if (checked) adloader->triggers[id].randomPosRadius = ui->sbTrigRandomRadius->value();
    else adloader->triggers[id].randomPosRadius = 0;
    if (lval != adloader->triggers[id].randomPosRadius) isSaved = false;
}


void MainWindow::on_cbTrigCount_toggled(bool checked)
{
    int id = adloader->triggers.values().at(ui->lvTriggers->currentIndex().row()).id;
    int lval = adloader->triggers[id].count;
    ui->sbTrigCount->setEnabled(checked);
    if (checked) adloader->triggers[id].count = ui->sbTrigCount->value();
    else adloader->triggers[id].count = 0;
    if (lval != adloader->triggers[id].count) isSaved = false;
}


void MainWindow::on_pbTrigAdd_clicked()
{
    int i = 1;
    while (adloader->triggers.contains(i)) i++;
    tbTrigger trig;
    trig.id = i;
    trig.name = tr("Trigger");
    trig.count = 0;
    trig.damage = 0;
    trig.radius = 0;
    trig.timer = 10;
    trig.chance = 100;
    trig.delParent =true ;
    trig.childAim = srcTriggerType::noAim;
    trig.randomPosRadius = 0;
    trig.type = srcTriggerType::onDestination;
    adloader->triggers.insert(trig.id,trig);
    int index = adloader->triggers.keys().indexOf(i);
    trigModel->refresh(adloader->triggers.values());
    ui->lvTriggers->reset();
    ui->lvTriggers->selectionModel()->setCurrentIndex(ui->lvTriggers->model()->index(index,0),QItemSelectionModel::ClearAndSelect);
    isSaved = false;
}


void MainWindow::on_pbTrigDel_clicked()
{
    if (adloader->triggers.size() < 2) return;
    QMessageBox msgBox;
    int id = adloader->triggers.keys().at(ui->lvTriggers->currentIndex().row());
    for (int i=0; i<adloader->chains.size(); i++)
    {
        if (adloader->chains.values().at(i).triggerId == id)
        {
            msgBox.setText(tr("You can not delete trigger %1 id=%2").arg(adloader->triggers.value(id).name).arg(id));
            msgBox.setInformativeText(tr("It used by chain in tower %1 id=%2").arg(adloader->towers.value(adloader->chains.values().at(i).towerId).name).arg(adloader->chains.values().at(i).towerId));
            msgBox.setStandardButtons(QMessageBox::Ok);
            msgBox.exec();
            return;
        }
    }
    msgBox.setText(tr("Delete trigger %1 id=%2").arg(adloader->triggers.value(id).name).arg(id));
    msgBox.setInformativeText(tr("Are you sure?"));
    msgBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel);
    msgBox.setDefaultButton(QMessageBox::Ok);
    int ret = msgBox.exec();
    if (ret == QMessageBox::Ok)
    {
        adloader->triggers.remove(id);
        trigModel->refresh(adloader->triggers.values());
        ui->lvTriggers->reset();
        ui->lvTriggers->selectionModel()->setCurrentIndex(ui->lvTriggers->model()->index(0,0),QItemSelectionModel::ClearAndSelect);
        isSaved = false;
    }
}


void MainWindow::on_cbTrigType_currentIndexChanged(int index)
{
    int id = adloader->triggers.values().at(ui->lvTriggers->currentIndex().row()).id;
    srcTriggerType::triggerType lval = adloader->triggers[id].type;
    adloader->triggers[id].type = (srcTriggerType::triggerType)ui->cbTrigType->itemData(index).toInt();
    if (adloader->triggers[id].type == srcTriggerType::onAlienInRadius)
    {
        ui->lbTrigChildAim->hide();
        ui->cbTrigChildAim->hide();
    } else {
        ui->lbTrigChildAim->show();
        ui->cbTrigChildAim->show();
    }
    if (adloader->triggers[id].type != srcTriggerType::onTimer)
    {
        ui->lbTrigTimer->setVisible(false);
        ui->sbTrigTimer->setVisible(false);
    } else {
        ui->lbTrigTimer->setVisible(true);
        ui->sbTrigTimer->setVisible(true);
        ui->sbTrigTimer->setValue(adloader->triggers[id].timer);
    }
    if (lval != adloader->triggers[id].type) isSaved = false;
}


void MainWindow::on_cbTrigChildAim_currentIndexChanged(int index)
{
    int id = adloader->triggers.values().at(ui->lvTriggers->currentIndex().row()).id;
    srcTriggerType::aimType lval = adloader->triggers[id].childAim;
    adloader->triggers[id].childAim = (srcTriggerType::aimType)ui->cbTrigChildAim->itemData(index).toInt();
    if (lval != adloader->triggers[id].childAim)isSaved = false;
}


void MainWindow::on_pbImgAdd_clicked()
{
    int id = adloader->animations.values().at(ui->lvAnimations->currentIndex().row()).id;
    QStringList strl;
    /*QFileDialog fd;
    fd.setNameFilter(tr());
    fd.setFileMode(QFileDialog::ExistingFiles);*/
    QDir dir;
    strl = QFileDialog::getOpenFileNames(this, "Select images", QString()/*qApp->applicationDirPath()*/, "Images (*.png)");
    /*if (fd.exec())
    {
        strl = fd.selectedFiles();*/
    for (int i=0; i<strl.size(); ++i)
    {
        strl[i] = dir.relativeFilePath(strl[i]);
    }
    adloader->animations[id].pathes.append(strl);
    refresh_lwImages(adloader->animations.value(id).pathes);
    isSaved = false;
    //}
}


void MainWindow::refresh_lwImages(QStringList pathes)
{
    ui->lwImages->clear();
    for (int i=0; i<pathes.size(); ++i)
    {
        ui->lwImages->addItem(new QListWidgetItem(QIcon(pathes.at(i)),pathes.at(i)));
    }
}


void MainWindow::on_pbImgDel_clicked()
{
    if (!ui->lwImages->selectedItems().isEmpty())
    {
        int id = adloader->animations.values().at(ui->lvAnimations->currentIndex().row()).id;
        for (int i=0; i<ui->lwImages->selectedItems().size(); ++i)
            adloader->animations[id].pathes.removeOne(ui->lwImages->selectedItems().at(i)->text());
        refresh_lwImages(adloader->animations.value(id).pathes);
        isSaved = false;
    }
}


void MainWindow::on_pbAnimAdd_clicked()
{
    int i = 1;
    while (adloader->animations.contains(i)) i++;
    tbAnimation anim;
    anim.id = i;
    adloader->animations.insert(anim.id,anim);
    int index = adloader->animations.keys().indexOf(i);
    //    animModel->refresh(adloader->animations.values());
    ui->lvAnimations->reset();
    ui->lvAnimations->selectionModel()->setCurrentIndex(ui->lvAnimations->model()->index(index,0),QItemSelectionModel::ClearAndSelect);
    isSaved = false;
}


void MainWindow::on_cbAlImage_currentIndexChanged(int index)
{
    if (!ui->lvAliens->currentIndex().isValid()) return;
    if (index >= 0)
    {
        int id = adloader->aliens.values().at(ui->lvAliens->currentIndex().row()).id;
        int lval = adloader->aliens[id].imgType;
        adloader->aliens[id].imgType = adloader->animations.values().at(index).id;
        ui->lbAlAnim->setAnimation(adloader->animations.value(adloader->aliens[id].imgType).pathes);
        if (lval != adloader->aliens[id].imgType) isSaved = false;
    }
}


void MainWindow::on_cbTwImage_currentIndexChanged(int index)
{
    if (!ui->lvTowers->currentIndex().isValid()) return;
    if (index >= 0)
    {
        int id = adloader->towers.values().at(ui->lvTowers->currentIndex().row()).id;
        int lval = adloader->towers[id].imgType;
        adloader->towers[id].imgType = adloader->animations.values().at(index).id;
        ui->lbTwAnim->setAnimation(adloader->animations.value(adloader->towers[id].imgType).pathes);
        if (lval != adloader->towers[id].imgType) isSaved = false;
    }
}


void MainWindow::on_cbSplImage_currentIndexChanged(int index)
{
    if (!ui->lvSplashes->currentIndex().isValid()) return;
    if (index >= 0)
    {
        int id = adloader->splashes.values().at(ui->lvSplashes->currentIndex().row()).id;
        int lval = adloader->splashes[id].imgType;
        adloader->splashes[id].imgType = adloader->animations.values().at(index).id;
        ui->lbSplAnim->setAnimation(adloader->animations.value(adloader->splashes[id].imgType).pathes);
        if (lval != adloader->splashes[id].imgType) isSaved = false;
    }
}

void MainWindow::on_pbAnimDel_clicked()
{
    if (adloader->animations.size() < 2) return;
    QMessageBox msgBox;
    int id = adloader->animations.keys().at(ui->lvAnimations->currentIndex().row());
    for (int i=0; i<adloader->towers.size(); i++)
    {
        if (adloader->towers.values().at(i).imgType == id)
        {
            msgBox.setText(tr("You can not delete anim %1").arg(id));
            msgBox.setInformativeText(tr("It used by tower %1 id=%2").arg(adloader->towers.values().at(i).name).arg(adloader->towers.values().at(i).id));
            msgBox.setStandardButtons(QMessageBox::Ok);
            msgBox.exec();
            return;
        }
    }
    for (int i=0; i<adloader->aliens.size(); i++)
    {
        if (adloader->aliens.values().at(i).imgType == id)
        {
            msgBox.setText(tr("You can not delete anim %1").arg(id));
            msgBox.setInformativeText(tr("It used by alien %1 id=%2").arg(adloader->aliens.values().at(i).name).arg(adloader->aliens.values().at(i).id));
            msgBox.setStandardButtons(QMessageBox::Ok);
            msgBox.exec();
            return;
        }
    }
    for (int i=0; i<adloader->splashes.size(); i++)
    {
        if (adloader->splashes.values().at(i).imgType == id)
        {
            msgBox.setText(tr("You can not delete anim %1").arg(id));
            msgBox.setInformativeText(tr("It used by splash %1 id=%2").arg(adloader->splashes.values().at(i).name).arg(adloader->splashes.values().at(i).id));
            msgBox.setStandardButtons(QMessageBox::Ok);
            msgBox.exec();
            return;
        }
    }
    msgBox.setText(tr("Delete anim %1").arg(id));
    msgBox.setInformativeText(tr("Are you sure?"));
    msgBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel);
    msgBox.setDefaultButton(QMessageBox::Ok);
    int ret = msgBox.exec();
    if (ret == QMessageBox::Ok)
    {
        adloader->animations.remove(id);
        //        animModel->refresh(adloader->animations.values());
        ui->lvAnimations->reset();
        ui->lvAnimations->selectionModel()->setCurrentIndex(ui->lvAnimations->model()->index(0,0),QItemSelectionModel::ClearAndSelect);
        isSaved = false;
    }
}


void MainWindow::on_cbSplCompisitionMode_currentIndexChanged(const QString &str)
{
    int id = adloader->splashes.values().at(ui->lvSplashes->currentIndex().row()).id;
    QPainter::CompositionMode lval = adloader->splashes[id].compositionMode;
    if (str == "NotSource") adloader->splashes[id].compositionMode = QPainter::RasterOp_NotSource;
    if (str == "Plus") adloader->splashes[id].compositionMode = QPainter::CompositionMode_Plus;
    if (str == "Multiply") adloader->splashes[id].compositionMode = QPainter::CompositionMode_Multiply;
    if (str == "Screen") adloader->splashes[id].compositionMode = QPainter::CompositionMode_Screen;
    if (str == "Overlay") adloader->splashes[id].compositionMode = QPainter::CompositionMode_Overlay;
    if (str == "Darken") adloader->splashes[id].compositionMode = QPainter::CompositionMode_Darken;
    if (str == "Lighten") adloader->splashes[id].compositionMode = QPainter::CompositionMode_Lighten;
    if (str == "ColorDodge") adloader->splashes[id].compositionMode = QPainter::CompositionMode_ColorDodge;
    if (str == "ColorBurn") adloader->splashes[id].compositionMode = QPainter::CompositionMode_ColorBurn;
    if (str == "HardLight") adloader->splashes[id].compositionMode = QPainter::CompositionMode_HardLight;
    if (str == "SoftLight") adloader->splashes[id].compositionMode = QPainter::CompositionMode_SoftLight;
    if (str == "Difference") adloader->splashes[id].compositionMode = QPainter::CompositionMode_Difference;
    if (lval != adloader->splashes[id].compositionMode) isSaved = false;
}


void MainWindow::on_sbSplZValue_valueChanged(double val)
{
    int id = adloader->splashes.values().at(ui->lvSplashes->currentIndex().row()).id;
    float lval = adloader->splashes[id].ZValue;
    adloader->splashes[id].ZValue = val;
    if (lval != adloader->splashes[id].ZValue) isSaved = false;
}


void MainWindow::on_sbSplAnimSpeed_valueChanged(double val)
{
    int id = adloader->splashes.values().at(ui->lvSplashes->currentIndex().row()).id;
    float lval = adloader->splashes[id].animSpeed;
    adloader->splashes[id].animSpeed = val;
    if (lval != adloader->splashes[id].animSpeed) isSaved = false;
}


void MainWindow::on_cbSplKeepOnAlien_toggled(bool checked)
{
    int id = adloader->splashes.values().at(ui->lvSplashes->currentIndex().row()).id;
    bool lval = adloader->splashes[id].keepOnAlien;
    adloader->splashes[id].keepOnAlien = checked;
    if (lval != adloader->splashes[id].keepOnAlien) isSaved = false;
}


void MainWindow::on_btWaveAddAlien_clicked()
{
    if (ui->lvWaveAliens->currentIndex().isValid())
        wavePartModel->insertAlien(adloader->aliens.values().at(ui->lvWaveAliens->currentIndex().row()).id);
    waveModel->refreshData();
}


void MainWindow::tbWavePartSelect(QModelIndex a, QModelIndex)
{
    ui->btWaveRemoveAlien->setEnabled(a.isValid());
}


void MainWindow::on_btWaveRemoveAlien_clicked()
{
    wavePartModel->removeAlien(ui->tableWaveParts->selectionModel()->currentIndex());
    waveModel->refreshData();
}


void MainWindow::on_btWaveClear_clicked()
{
    wavePartModel->clearAliens();
    waveModel->refreshData();
}


void MainWindow::on_pbWaveAdd_clicked()
{
//    wavePartModel->setCurrentWave(QModelIndex());
    QModelIndex a = ui->tableWaves->selectionModel()->currentIndex();
    waveModel->addWave(a);
    wavePartModel->setCurrentWave(waveModel->index(a.row()+1,a.column()));
    //wavePartModel->setCurrentWave(a);
//    ui->tableWaves->selectionModel()->setCurrentIndex(waveModel->index(a.row()+1,a.column()),QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
}


void MainWindow::on_pbWaveDel_clicked()
{
//    wavePartModel->setCurrentWave(QModelIndex());
    QModelIndex a = ui->tableWaves->selectionModel()->currentIndex();
    waveModel->removeWave(a);
    wavePartModel->setCurrentWave(waveModel->index(a.row(),a.column()));
    //wavePartModel->setCurrentWave(a);
    //ui->tableWaves->selectionModel()->setCurrentIndex(waveModel->index(a.row(),a.column()),QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
}


void MainWindow::on_pbWaveCopy_clicked()
{
//    wavePartModel->setCurrentWave(QModelIndex());
    QModelIndex a = ui->tableWaves->selectionModel()->currentIndex();
    waveModel->copyWave(a);
    wavePartModel->setCurrentWave(waveModel->index(a.row()+1,a.column()));
//    ui->tableWaves->selectionModel()->setCurrentIndex(waveModel->index(a.row()+1,a.column()),QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
}


void MainWindow::on_btWaveUp_clicked()
{
    wavePartModel->setCurrentWave(QModelIndex());
    QModelIndex a = ui->tableWaves->selectionModel()->currentIndex();
    waveModel->upWave(a);
    ui->tableWaves->selectionModel()->setCurrentIndex(waveModel->index(a.row()-1,a.column()),QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
}


void MainWindow::on_btWaveDown_clicked()
{
    wavePartModel->setCurrentWave(QModelIndex());
    QModelIndex a = ui->tableWaves->selectionModel()->currentIndex();
    waveModel->downWave(a);
    ui->tableWaves->selectionModel()->setCurrentIndex(waveModel->index(a.row()+1,a.column()),QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
}
