#include "utauSettingTableWidget.h"
#include <QFile>
#include <QTextDecoder>
#include <QHeaderView>

const int TableColumnCount = 7;
const int defaultRowHeight = 20;

bool utauSettingTableWidget::getParametersByAlias(QString &alias, QUtauParameters &dst)
{
    bool ret = false;
    QList<QTableWidgetItem*> items;
    QString search = alias;
    if(suffix){
        search = search + suffix->text();
    }
    items = this->findItems(search, Qt::MatchExactly);
    if(items.size() > 0){
        getParametersInRow(items.at(0)->row(), dst);
        ret = true;
    }
    return ret;
}

void utauSettingTableWidget::getParametersInRow(int row, QUtauParameters &param)
{
    param.directoryPath = this->directoryPath;
    for(int i = 0; i < 7; i++){
        QTableWidgetItem *thisItem = this->item(row, i);
        switch(i){
        case 0:
            param.fileName = this->directoryPath + thisItem->text();
            break;
        case 1:
            param.alias = thisItem->text();
            break;
        case 2:
            param.leftBlank = thisItem->text().toFloat();
            break;
        case 3:
            param.fixedLength = thisItem->text().toFloat();
            break;
        case 4:
            param.rightBlank = thisItem->text().toFloat();
            break;
        case 5:
            param.preUtterance = thisItem->text().toFloat();
            break;
        case 6:
            param.voiceOverlap = thisItem->text().toFloat();
            break;
        }
    }
}

void utauSettingTableWidget::selectionCheck()
{
    QModelIndexList indexList = this->selectedIndexes();
    if(indexList.size() < TableColumnCount) return;

    int tmp = indexList.at(0).row();
    for(int i = 1; i < indexList.size(); i++){
        if(tmp != indexList.at(i).row()){ return; }
    }
    this->getParametersInRow(tmp, current);
    // サフィックスは一応消しておく
    if(suffix){
        current.alias.remove(suffix->text());
    }
    emit(this->updateWaveView(&current));
}

void utauSettingTableWidget::searchAndSelectByParameters(QUtauParameters *p)
{
    QString search = p->alias;
    QList<QTableWidgetItem*> items;
    if(suffix){
        search = p->alias + suffix->text();
    }
    items = this->findItems(search, Qt::MatchExactly);
    if(items.size() != 0){
        this->selectRow(items.at(0)->row());
        this->selectionCheck();
        emit(enableAnalysis(TRUE));
    }else{
        emit(enableAnalysis(FALSE));
    }
}

void utauSettingTableWidget::setRowHeightAtTime(int rowHeight)
{
    QHeaderView *header = this->verticalHeader();
    header->setUpdatesEnabled(FALSE);
    for(int i = 0; i < this->rowCount(); i++){
        header->resizeSection(i, rowHeight);
    }
    header->setUpdatesEnabled(TRUE);
}


void utauSettingTableWidget::setSettingFilePath(QString *s)
{
    QFile openFile(*s);
    qDebug("---begin reading oto.ini");
    if(openFile.open(QIODevice::ReadOnly | QIODevice::Text)){
        QString currentLine;
        QTextCodec::setCodecForCStrings(QTextCodec::codecForLocale());
        this->destroyAllItems();
        this->clearContents();
        int row = 0;

        this->filePath = *s;
        this->directoryPath = this->filePath;
        this->directoryPath.remove(QRegExp("oto.ini"));

        while(!openFile.atEnd()){
            QStringList tmp;
            QByteArray line = openFile.readLine();
            currentLine = QString::fromLocal8Bit(line.data());
            // 行内に含まれる区切り文字は '=', ',' に設定して StringList へ分割する．
            tmp = currentLine.split(QRegExp("[=,]"), QString::KeepEmptyParts);
            this->setRowCount(row+1);
            for(int i = 0; i < columnCount(); i++){
                if(i >= tmp.size()) break;
                QTableWidgetItem *thisItem;
                thisItem = new QTableWidgetItem();
                thisItem->setText(tmp.at(i));
                this->setItem(row, i, thisItem);
            }
            row++;
        }
        openFile.close();
        this->setRowHeightAtTime(defaultRowHeight);
        this->show();
        qDebug("succeeded");
    }else{
        qDebug("failed open file");
    }

}

utauSettingTableWidget::utauSettingTableWidget(QWidget *parent) :
    QTableWidget(parent)
{
    QStringList headerLabels;
    this->setColumnCount(TableColumnCount);

    headerLabels << "FileName"
                 << "Alias"
                 << "l.Blank"
                 << "Fixed"
                 << "r.Blank"
                 << "Pre"
                 << "Overlap";
    this->setHorizontalHeaderLabels(headerLabels);
    this->horizontalHeader()->resize(this->width(), defaultRowHeight);
    this->setColumnWidth(0,100);
    this->setColumnWidth(1,60);
    this->setColumnWidth(2,50);
    this->setColumnWidth(3,50);
    this->setColumnWidth(4,50);
    this->setColumnWidth(5,50);
    this->setColumnWidth(6,50);
    this->setRowCount(1);
    for(int i = 0; i < this->columnCount(); i++){
        this->setItem(0, i, new QTableWidgetItem(tr("n/a")));
    }
    this->setRowHeightAtTime(defaultRowHeight);

    this->suffix = NULL;
}

void utauSettingTableWidget::destroyAllItems(void)
{
    for(int i = 0; i < this->columnCount(); i++){
        for(int j = 0; j < this->rowCount(); j++){
            QTableWidgetItem *p;
            p = this->itemAt(i,j);
            if(p){delete p;}
        }
    }
}
