#include "mainwidget.h"
#include "ui_mainwidget.h"

#include <QFileDialog>
#include <QTextBlock>
#include <QDesktopServices>
#include <QMessageBox>
#include <QDateTime>

#include "processthread.h"

MainWidget::MainWidget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::MainWidget)
{
    ui->setupUi(this);

    initUI();
    connects();
}

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

void MainWidget::initUI()
{
    // ui->inputTextEdit->setDragFilter(QStringList() << "obj");

    ConfigParam p = Global::Instance()->configParam();
    for(auto i : p.inputPaths)
    {
        ui->inputTextEdit->append(i);
    }
    ui->outputLineEdit->setText(p.outputPath);   

    mThread = new ProcessThread(this);

    mColorList << "#C9CDD1"; // 0灰白色，普通信息
    mColorList << "#428EDA"; // 1蓝色，提示信息
    mColorList << "#F28627"; // 2橙色，警告信息
    mColorList << "#F22776"; // 3红色，致命信息
    mColorList << "#1CC929"; // 4绿色，未知信息

    mLightColorList << "#43BE32"; // 0绿色 表示正在运行
    mLightColorList << "#E52C5E"; // 1红色 表示未运行

    ui->lightWidget->setBgColor(mLightColorList.at(1));
}

void MainWidget::connects()
{
    connect(ui->selectInputButton, &QPushButton::clicked, this, &MainWidget::selectInput);
    connect(ui->selectOutputButton, &QPushButton::clicked, this, &MainWidget::selectOutput);
    connect(ui->clearInputButton, &QPushButton::clicked, this, [=](){
        ui->inputTextEdit->clear();
    });
    connect(ui->openInputDirButton, &QPushButton::clicked, this, &MainWidget::openInputDir);
    connect(ui->openOutputDirButton, &QPushButton::clicked, this, &MainWidget::openOutputDir);

    connect(ui->startButton, &QPushButton::clicked, this, &MainWidget::start);
    connect(ui->cancelButton, &QPushButton::clicked, this, &MainWidget::cancel);
    connect(ui->quitButton, &QPushButton::clicked, this, &MainWidget::slotQuit);

    connect(mThread, &QThread::finished, this, &MainWidget::processCompleted);
    connect(mThread, &ProcessThread::tip, this, &MainWidget::debugTip);
}

void MainWidget::getLastDir()
{
    QString plainText = ui->inputTextEdit->toPlainText();
    if(plainText.isEmpty())
    {
        ConfigParam p = Global::Instance()->configParam();
        if(p.inputPaths.size())
        {
            QString lastPath = p.inputPaths.first();

            if(!lastPath.isEmpty())
            {
                QFileInfo info(lastPath);
                if(info.exists() && info.isDir())
                {
                    mLastDirPath = lastPath;
                }
            }
        }

    }
    else
    {
        QTextDocument* pDocument = ui->inputTextEdit->document();
        QTextBlock block = pDocument->begin();
        while (block.isValid() && block.layout())
        {
            QString strBlock = block.text();
            QFileInfo info(strBlock);
            if(info.isFile())
            {
                if(info.dir().exists())
                {
                    mLastDirPath = info.dir().path();
                    break;
                }
            }
            else
            {
                if(info.exists())
                {
                    mLastDirPath = strBlock;
                    break;
                }
            }
            block = block.next();
        }
    }
    if(mLastDirPath.isEmpty())
    {
        mLastDirPath = qApp->applicationDirPath();
    }
}

QStringList MainWidget::selectedFileNames()
{
    QStringList fileNames;
    QTextDocument* pDocument = ui->inputTextEdit->document();
    QTextBlock block = pDocument->begin();
    while (block.isValid() && block.layout())
    {
        QString strBlock = block.text();
        QFileInfo info(strBlock);
//        if(info.isFile() && info.exists())
//        {
//            fileNames.append(strBlock);
//        }
        fileNames.append(strBlock);

        block = block.next();
    }
    return fileNames;
}

ConfigParam MainWidget::getConfigParam()
{
    ConfigParam p;
    p.inputPaths = selectedFileNames();
    p.outputPath = ui->outputLineEdit->text();
    return p;
}

void MainWidget::selectInput()
{
    getLastDir();

    QStringList files = QFileDialog::getOpenFileNames(
        this,
        "选择多个obj文件",
        mLastDirPath,
        "obj文件 (*.obj)");
    if(!files.empty())
    {
        // ui->inputTextEdit->clear();
        foreach (QString var, files)
        {
            ui->inputTextEdit->append(var);
        }
    }

    Global::Instance()->setInput(selectedFileNames());
}

void MainWidget::selectOutput()
{
    QString lastDirPath;
    QFileInfo info(ui->outputLineEdit->text());
    if (info.dir().exists())
    {
        lastDirPath = info.dir().path();
    }
    else
    {
        lastDirPath = QDir::currentPath();
    }
    QString fileName = QFileDialog::getSaveFileName(this, "保存obj文件",
                                                    lastDirPath,
                                                    "obj文件 (*.obj)");
    if (fileName.isEmpty())
        return;
    ui->outputLineEdit->setText(fileName);

    Global::Instance()->setOutput(fileName);
}

void MainWidget::openInputDir()
{
    QStringList list = selectedFileNames();
    QString lastDir;
    if(list.size())
    {
        QFileInfo info(list.first());
        lastDir = info.dir().path();
    }
    else
    {
        lastDir = qApp->applicationDirPath();
    }
    QDesktopServices::openUrl(QUrl::fromLocalFile(lastDir));
}

void MainWidget::openOutputDir()
{
    QFileInfo info(ui->outputLineEdit->text());
    if (info.dir().exists())
    {
        QDesktopServices::openUrl(QUrl::fromLocalFile(info.dir().path()));
    }
}

void MainWidget::start()
{
    if(mThread->isRunning())
    {
        QMessageBox msgBox;
        msgBox.setWindowTitle("提示");
        msgBox.setText("正在处理模型，请稍等");
        msgBox.exec();
        return;
    }

    ConfigParam p = getConfigParam();
    if(p.inputPaths.size() == 0)
    {
        QMessageBox msgBox;
        msgBox.setWindowTitle("提示");
        msgBox.setText("请输入obj模型");
        msgBox.exec();
        return;
    }

    if(p.outputPath.isEmpty())
    {
        QMessageBox msgBox;
        msgBox.setWindowTitle("提示");
        msgBox.setText("请输入保存obj模型路径");
        msgBox.exec();
        return;
    }

    QFileInfo info(p.outputPath);
    if(info.exists())
    {

        QMessageBox::StandardButton button = QMessageBox::question(this, "提示", p.outputPath + "文件已经存在，是否覆盖?",
                    QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
        if(button == QMessageBox::No)
        {
            return;
        }
    }

    Global::Instance()->setConfigParam(p);
    mThread->setParam(p);
    ui->timeWidget->start();

    debugTip("模型开始处理", 0, true);
    ui->lightWidget->setBgColor(mLightColorList.at(0));

    mThread->start();
}

void MainWidget::cancel()
{
    if(mThread->isRunning())
    {
        mThread->terminate();
        debugTip("模型停止处理", 0, true);
    }
    else
    {
        debugTip("模型处理为运行", 0, true);
    }
    ui->lightWidget->setBgColor(mLightColorList.at(1));
}

void MainWidget::slotQuit()
{
    if(mThread->isRunning())
    {
        QMessageBox::StandardButton button = QMessageBox::question(this, "提示", "正在处理模型，确定退出?",
                    QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
        if(button == QMessageBox::No)
        {
            return;
        }
    }
    this->close();
    std::exit(0);
}

void MainWidget::processCompleted()
{
    ui->timeWidget->stop();
    debugTip("模型处理完成", 0, true);
    ui->lightWidget->setBgColor(mLightColorList.at(1));

    QMessageBox msgBox;
    msgBox.setWindowTitle("提示");
    msgBox.setText("模型处理完成");
    msgBox.exec();
}

void MainWidget::debugTip(const QString &txt, int index, bool addTime)
{
    if(index >= 0 && index <= 3)
    {
        if(addTime)
        {
            ui->textBrowser->append(QString("<font color=\"%1\">%2->%3</font>")
                                        .arg(mColorList.at(index))
                                        .arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz"))
                                        .arg(txt));

        }
        else
        {
            ui->textBrowser->append(QString("<font color=\"%1\">%2</font>").arg(mColorList.at(index)).arg(txt));
        }
    }
    else
    {
        if(addTime)
        {
            ui->textBrowser->append(QString("<font color=\"%1\">%2[未知信息]->%3</font>")
                                        .arg(mColorList.at(index))
                                        .arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz"))
                                        .arg(txt));
        }
        else
        {

            ui->textBrowser->append(QString("<font color=\"%1\">[未知信息]%2</font>").arg(mColorList.at(index)).arg(txt));
        }
    }
}

