#include "phonemetableview.h"
#include "ui_phonemetableview.h"
#include <QMessageBox>
#include <QFileDialog>
#include <QTableWidgetItem>
#include <QProgressBar>

#include "progresswindow.h"

enum overwriteState{
    YES_TO_ALL,
    NO_TO_ALL,
    ALWAYS_CHECK,
};

void phonemeTableView::saveAll(QString &directoryPath)
{
    overwriteState overwrite;
    QUtauParameters src, dst;
    progressWindow *window = new progressWindow(this);

    if(ui->overwriteCheckBox->checkState()){
        overwrite = ALWAYS_CHECK;
    }else{
        overwrite = YES_TO_ALL;
    }
    int rowCount = ui->sourceSettings->rowCount();
    window->show();
    for(int i = 0; i < rowCount; i++){
        QString output;
        // Cancel が押されているかチェックする．
        if(window->cancel()){ break; }
        window->setProgressValue(100 * i / rowCount);
        window->setLabelText(QString("%1/%2").arg(i).arg(rowCount));
        window->update();
        // 条件にマッチしないものは外していく．
        ui->sourceSettings->getParametersInRow(i, src);
        if(ui->additionalSettings->getParametersByAlias(src.alias, dst) == false){ continue; }
        if(!QFile::exists(src.fileName) || !QFile::exists(dst.fileName)){ continue; }
        output = directoryPath + src.alias + ".stt";

        if(QFile::exists(output)){
            switch(overwrite){
            case NO_TO_ALL:
                continue;
            case ALWAYS_CHECK:
                QMessageBox::StandardButton makeSureDialog;
                makeSureDialog = QMessageBox::question(this, this->windowTitle(), tr("Do you want to over write the file:\n") + output,
                                               QMessageBox::Yes | QMessageBox::YesToAll | QMessageBox::No | QMessageBox::NoToAll);
                switch(makeSureDialog){ // これはちょっと酷いか…
                case QMessageBox::NoToAll:
                    overwrite = NO_TO_ALL;
                case QMessageBox::No:
                    continue;
                case QMessageBox::YesToAll:
                    overwrite = YES_TO_ALL;
                case QMessageBox::Yes:
                    break;
                }
                break;
            case YES_TO_ALL:
                break;
            }
        }
        // ここから分析・保存処理
        this->analysisViewer->setParameters(src, dst, false);
        this->analysisViewer->saveMelCepstrum(output);
    }
    delete window;
}

void phonemeTableView::generateAll(void)
{
    QString directoryPath;

    directoryPath = QFileDialog::getSaveFileName(this, tr("Generate stt files")
                                                 ,ui->sourceSettings->getDirectoryPath() + "dummy"
                                                 ,"dummy", &QString("stt file (*.stt)"), QFileDialog::DontConfirmOverwrite);
    if(QString::compare(directoryPath, QString("")) == 0){
        return;
    }
    directoryPath = directoryPath.remove(QDir(directoryPath).dirName());
    // ディレクトリがかぶるときの対応．
    if(QString::compare(directoryPath, ui->sourceSettings->getDirectoryPath()) == 0 ||
       QString::compare(directoryPath, ui->additionalSettings->getDirectoryPath()) == 0){
        QMessageBox::StandardButton dialog;
        dialog = QMessageBox::question(this, this->windowTitle(),
                                       tr("Do you want to generate files at the root of the library?\nIt is strongly recommended to save at another directory."),
                                       QMessageBox::Yes | QMessageBox::No);
        if(dialog == QMessageBox::No){
            return;
        }
    }
    this->analysisViewer->close();
    saveAll(directoryPath);
}

void phonemeTableView::selectKey(void)
{
    QList<QTableWidgetItem*> itemList;
    itemList = ui->sourceSettings->findItems(ui->searchKey->text(),Qt::MatchExactly);
    if(itemList.size()){
        ui->sourceSettings->selectRow(itemList.at(0)->row());
    }
}

void phonemeTableView::analyze(void)
{
    QUtauParameters src, dst;
    ui->sourceSettings->getCurrentParameters(src);
    ui->additionalSettings->getCurrentParameters(dst);
    analysisViewer->setParameters(src, dst);
    analysisViewer->show();
}

void phonemeTableView::openSetting(void)
{
    sourcePath = getSettingFilePath();
    if(QString::compare(sourcePath, tr("")) != 0){
        emit(settingPathOpened(&sourcePath));
    }
    ui->sourceFilePath->setText(sourcePath);
}

void phonemeTableView::importSetting(void)
{
    additionalPath = getSettingFilePath();
    if(QString::compare(additionalPath, tr("")) != 0){
        emit(settingPathImported(&additionalPath));
    }
    ui->additionalFilePath->setText(additionalPath);
}

QString phonemeTableView::getSettingFilePath(void)
{
    QString ret = "", filter;

    QFileDialog dialog(this, tr("Select oto.ini"), QDir::currentPath());

    filter = "otoIniFile (oto.ini)";
    dialog.setNameFilter(filter);
    dialog.setAcceptMode(QFileDialog::AcceptOpen);

    ret = dialog.getOpenFileName(this, tr("OpenFile"), QDir::currentPath(), filter, NULL, NULL);

    return ret;
}

void phonemeTableView::makeSureExit(void)
{
    QMessageBox::StandardButton dialog;
    dialog = QMessageBox::question(this, this->windowTitle(), tr("Do you want to exit?"), QMessageBox::Yes | QMessageBox::No);
    if(dialog == QMessageBox::Yes){
        this->close();
    }
}

void phonemeTableView::waveScaleChange(int value)
{
    double scale;
    scale = pow(2.0, 3.0 - (double)value);
    ui->scaleLabel->setText(tr("%1 ms/px").arg(1 / scale, 2));
    emit(scaleChange(scale));
}

void phonemeTableView::enableAnalysis(bool flag)
{
    ui->analyzeButton->setEnabled(flag);
}

phonemeTableView::phonemeTableView(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::phonemeTableView)
{
    ui->setupUi(this);
    // set shortcut key
    ui->action_Open->setShortcut(tr("Ctrl+O"));
    ui->action_Import->setShortcut(tr("Ctrl+I"));

    ui->sourceSettings->setSuffixTextObject(ui->sourceSuffix);
    ui->additionalSettings->setSuffixTextObject(ui->additionalSuffix);
    ui->scaleSlider->setValue(3);
    analysisViewer = new analysisWindow(this);
    analysisViewer->hide();
}

phonemeTableView::~phonemeTableView()
{
    delete ui;
    delete analysisViewer;
}

void phonemeTableView::on_action_Exit_triggered()
{
    makeSureExit();
}

void phonemeTableView::on_action_Open_triggered()
{
    openSetting();
}


void phonemeTableView::on_action_Import_triggered()
{
    importSetting();
}
