#include "scriptlistmodel.h"

#define _CONSOLE_ERROR( x ) emit sendConsoleOut(QString() + x , ConsoleOut::Error);
#define _CONSOLE_INFO( x ) emit sendConsoleOut(QString() + x , ConsoleOut::Information);
#define _CONSOLE_VERBOSE( x ) emit sendConsoleOut(QString() + x , ConsoleOut::Verbose);
#define _CONSOLE_FATAL( x ) emit sendConsoleOut(QString() + x , ConsoleOut::Fatal);

ScriptListModel::ScriptListModel(QObject *parent, QString *scriptsFolderPath) :
        QAbstractListModel(parent), scriptsFolderPath(scriptsFolderPath) {
    //TODO: Add Error Checking
    this->refresh();
}

void ScriptListModel::refresh(){

    if(nameList.size()!=0){
        this->beginRemoveRows(QModelIndex(), 0, nameList.size()-1);
        nameList.clear();
        descriptionList.clear();
        requireList.clear();
        optionalList.clear();
        returnList.clear();
        this->endRemoveRows();
    }
    QFile *f;
    QString in;
    QString path;
    QList<QString> data;

    QDirIterator it(*scriptsFolderPath, QDir::Files | QDir::Readable | QDir::NoDotAndDotDot |
                    QDir::NoSymLinks, QDirIterator::NoIteratorFlags);
     while (it.hasNext()) {
         path = it.next();  //next returns path
         f = new QFile(path);
         if(!f->open(QIODevice::ReadOnly)){
             _CONSOLE_ERROR("Failed to open script File: " + f->fileName());
             continue;
         }
         QTextStream s(f);
         in = s.readLine();
         if(in != "#SonifyScript"){
             in = s.readLine();
             if(in != "#SonifyScript"){
                 _CONSOLE_VERBOSE("Ignoring Script File (no header): " + f->fileName());
                 f->close();
                 continue;
             }
         }
         this->beginInsertRows(QModelIndex(), nameList.size(), nameList.size());
         nameList << it.fileName().split('.')[0];
         this->endInsertRows();
         pathList << it.filePath();
         requireList << ""; optionalList << ""; descriptionList << ""; returnList << "";
         while(!s.atEnd()){
             in = s.readLine();
             data = in.split(':');
             if(data.isEmpty()){
                 _CONSOLE_INFO("Empty segment in header for " + f->fileName() +
                                     "Forgotten an #End tag??");
                 break;
             }
             QString d = data[0].toLower().trimmed();
             if (d == "#require" || d == "#requires" || d == "#required"){
                 requireList.last() = data[1].trimmed();
                 continue;}
             if (d == "#optional" || d == "#optionals"){
                 optionalList.last() = data[1].trimmed();
                 continue;}
             if (d == "#description"){
                 descriptionList.last() = data[1].trimmed();
                 continue;}
             if (d == "#return" || d == "#returns" || d == "#returned"){
                 returnList.last() = data[1].trimmed();
                 continue;}
             if (d == "#end"){
                 break;}
             //Should be done with console
             _CONSOLE_ERROR("Unknown Item in header: " + f->fileName());
         }
         f->close();
     }
}

int ScriptListModel::rowCount(const QModelIndex &parent) const
{
    return nameList.count();
}

QVariant ScriptListModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid())
        return QVariant();

    if (index.row() >= nameList.size())
        return QVariant();

    if (role == Qt::DisplayRole)
        return nameList.at(index.row());
    else
        return QVariant();
}

QVariant ScriptListModel::headerData(int section, Qt::Orientation orientation,
                                     int role) const
{
    if (role != Qt::DisplayRole)
        return QVariant();

    if (orientation == Qt::Horizontal)
        return QString("Script Name").arg(section);
    else
        return QString("Row %1").arg(section);
}


QString ScriptListModel::getName(int row){
    if(row >=0 && row < nameList.size()){return nameList[row];}
    return "";
}
QString ScriptListModel::getPath(int row){
    if(row >=0 && row < nameList.size()){return pathList[row];}
    return "";
}
QString ScriptListModel::getRequire(int row){
    if(row >=0 && row < requireList.size()){return requireList[row];}
    return "";
}
QString ScriptListModel::getOptional(int row){
    if(row >=0 && row < optionalList.size()){return optionalList[row];}
    return "";
}
QString ScriptListModel::getDecription(int row){
    if(row >=0 && row < descriptionList.size()){return descriptionList[row];}
    return "";
}
QString ScriptListModel::getReturn(int row){
    if(row >=0 && row < returnList.size()){return returnList[row];}
    return "";
}
