//  Copyright (2010-2013) Cédric Coussinet (cedric.coussinet@nomoseed.net)
//
//  This program is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published
//  by the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with this program. If not, see <http://www.gnu.org/licenses/>

#include "pointsscatterui.h"

#include <QFile>
#include <QStringList>
#include <QProcess>
#include <QDir>

#if WIN32
const QString Rscript = "R/bin/Rscript";
#else
const QString Rscript = "Rscript";
#endif

bool isValidPointsscatterCSV(const QString filename){
    QFile originPointsFile (filename);
    QFile pointsFile ("local.csv");
    QString line;
    QStringList header;
    int lines_nbr = 0;
    originPointsFile.open(QIODevice::ReadOnly);
    line = originPointsFile.readLine();
    QString dataString;
    dataString.append("pch,cex," + line);
    header = line.split(",");
    line = originPointsFile.readLine();
    if (header.size() < 3 || header.at(0) != "time" || header.at(1) != "label" || line.split(",").at(0).toInt() < 1)
        return false;
    const int dim_nbr = header.size();
    do{
        dataString.append("1,1," + line);
        if (line.split(",").size() != dim_nbr)
            return false;
        line = originPointsFile.readLine();
        lines_nbr++;
    } while (line.split(",").at(0).toInt() > 0);
    if (lines_nbr<2)
        return false;
    QStringList labelString;
    QStringList clusterString;
    while (line != ""){
        if (line.split(",").at(0).toInt() != 0)
            labelString.append("20,1," + line);
        else
            clusterString.append("3,5," + line);
        line = originPointsFile.readLine();
        dataString.append(line);
    };
    if (!dataString.endsWith("\n"))
        dataString = dataString + "\n";
    originPointsFile.reset();
    originPointsFile.readLine();
    for (int i=0; i < lines_nbr; i++) {
        line = originPointsFile.readLine();
    }
    originPointsFile.close();
    pointsFile.open(QIODevice::WriteOnly);
    pointsFile.write((dataString + labelString.join("") + clusterString.join("")).toUtf8().constData());
    pointsFile.close();
    return true;
}

xmlDocPtr getSVGPointsscatterCSV (const QString yLab){
    QStringList arguments;
    arguments << "points.r";
    arguments << "\"" + QDir::currentPath () + "\"";
    arguments << "\""+yLab.toUtf8()+"\"";
    QProcess rProcess;

 /*   QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
    env.insert("LD_LIBRARY_PATH", ".");
    QStringList test(QProcess::systemEnvironment());
    qWarning(test.join(" ").toUtf8().data());
    rProcess->setProcessEnvironment(env);*/

    rProcess.start(Rscript, arguments);
    if (!rProcess.waitForFinished())
        return NULL;
    return xmlReadFile("points.svg", NULL, 0 );
}

void updateSVGPointsscatterCSV (const QString yLab){
    QStringList arguments;
    arguments << "points.r";
    arguments << "\"" + QDir::currentPath () + "\"";
    arguments << "\"" + yLab.toUtf8() + "\"";
    QProcess rProcess;
    rProcess.start(Rscript, arguments);
    rProcess.waitForFinished();
}

void saveDataPointsscatterCSV (const QString filename){
    QFile localFile ("local.csv");
    localFile.open(QIODevice::ReadOnly);
    QString line;
    QStringList data;
    QStringList result;
    int cmp = 0;
    line = localFile.readLine();
    while (line != ""){
        data = line.split(',');
        if (data.at(0).toInt() != 23){
            if (data.at(0).toInt() == 3)
                cmp++;
            data.removeFirst();
            data.removeFirst();
        }
        result.append(data.join(","));
        line = localFile.readLine();
    };
    localFile.close();
    if (result.last().split(',').at(0).toInt()<0)
        result.move(result.length()-1,result.length()-1-cmp);
    QFile targetFile (filename);
    targetFile.open(QIODevice::WriteOnly);
    targetFile.write(result.join("\n").toUtf8());
    targetFile.close();
}
