#include "editscreen.h"
#include "ui_editscreen.h"
#include <Controller/mainwindowcontroller.h>
#include <QFileDialog>
#include <QMimeData>
#include <QGraphicsOpacityEffect>
#include <QPropertyAnimation>

EditScreen::EditScreen(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::EditScreen)
{
    ui->setupUi(this);
    enableDragAndDrop();
    setWindowFlags(Qt::WindowCloseButtonHint);
}

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

void EditScreen::setController(MainWindowController *controller)
{
    this->controller = controller;
}

void EditScreen::enableDragAndDrop()
{
    setAcceptDrops(true);
}

void EditScreen::on_browseBtn_clicked()
{
    QString fileName = QFileDialog::getOpenFileName(this,tr("Seleccione un fichero"), QDir::currentPath(), "Qml files (*.qml)", nullptr, QFileDialog::DontUseNativeDialog);
    controller->editScreenFromFile(fileName);
}

void EditScreen::dragEnterEvent(QDragEnterEvent *event)
{
    if (event->mimeData()->hasUrls()) {
            event->acceptProposedAction();
            showImageAnimation(1,0);
            ui->imageBtn->setIcon(QIcon(QPixmap(":/resources/icon/qmlExtension.png").scaled(200,200,Qt::KeepAspectRatio, Qt::SmoothTransformation)));
            showImageAnimation(0,1);
        }
}

void EditScreen::dropEvent(QDropEvent *event)
{
    QList<QUrl> urls = event->mimeData()->urls();
    QString fileName = urls.at(0).toLocalFile();
    QFileInfo fileInfo(fileName);
    if(fileInfo.suffix() == "qml")
    {
        showImageAnimation(1,0);
        ui->imageBtn->setIcon(QIcon(QPixmap(":/resources/icon/success.png").scaled(200,200,Qt::KeepAspectRatio, Qt::SmoothTransformation)));
        showImageAnimation(0,1);
        controller->editScreenFromFile(fileName);
    }
    else
    {
        showDragError();
    }
}

void EditScreen::showImageAnimation(int start, int end)
{
    QGraphicsOpacityEffect *eff = new QGraphicsOpacityEffect(this);
    ui->imageBtn->setGraphicsEffect(eff);
    QPropertyAnimation *a = new QPropertyAnimation(eff,"opacity");
    a->setDuration(250);
    a->setStartValue(start);
    a->setEndValue(end);
    a->setEasingCurve(QEasingCurve::InBack);
    a->start(QPropertyAnimation::DeleteWhenStopped);

}

void EditScreen::showDragError()
{
    showImageAnimation(1,0);
    ui->imageBtn->setIcon(QIcon(QPixmap(":/resources/icon/error.png").scaled(200,200,Qt::KeepAspectRatio, Qt::SmoothTransformation)));
    showImageAnimation(0,1);

}

