#include "projections.h"
#include <QProcess>
#include <QTextStream>

Projections* Projections::instance = NULL;


Projections* Projections::getInstance()
{
    if (!instance)
        instance = new Projections();
    return instance;
}

Projections::Projections()
{
    projections = new QVector<Projection>();
    list_projs_names = new QStringList();
    generateProjections();
}

void Projections::generateProjections() {

    //QVector<Projection> projections;

    QString proj_dir;
    QProcess *ini = new QProcess();
    ini->start("which proj");
    ini->waitForFinished();
    if(ini->exitCode()==1)
    {
        throw "proj not found";
    }
    else
    {
        proj_dir = ini->readAllStandardOutput();
    }

        QProcess *proj_cmd = new QProcess();
        proj_cmd->start(proj_dir + " -lp");
        proj_cmd->waitForFinished();
        QTextStream output (proj_cmd->readAllStandardOutput());

        // PARSE ELLIPSOIDS OUTPUT
        QString *line = new QString();
        QString *proj_identifier = new QString();
        QString *proj_description = new QString();
        QString *tmp2 = new QString();
        Projection *proj = new Projection();

        while(!output.atEnd())
        {
            *line = output.readLine(0); //READ LINE
            proj_description->clear();   //CLEAR DESCRIPTION

            //PARSE ONE LINE (ONE ELLIPSOID)
            QTextStream output2 (line); //RETYPE STRING TO STREAM
            output2 >> *proj_identifier;
            proj->setIdentifier(*proj_identifier);

            // REMOVE ":" FROM OUTPUT
            output2 >> *tmp2;
            tmp2->clear();

            while(!output2.atEnd())
            {
                output2 >> *tmp2;
                *proj_description += " ";
                *proj_description += *tmp2;
            }
            proj->setDescription(*proj_description);
            list_projs_names->append(*proj_description);
            projections->push_back(*proj);
        }
}

QVector<Projection> *Projections::getProjs(){
    return projections;
}

QString Projections::findProjection(QString projection_description){

    for(QVector<Projection>::iterator i=projections->begin();i!=projections->end();i++)
    {
        if(i->getDescription()==projection_description)
        {
            return i->getIdentifier();
        }
    }
    throw "Projection not found";
}

Projection Projections::begin(){
    return *projections->begin();
}

Projection Projections::end(){
    return *projections->end();
}
/*
bool Projections::operator= (Projections projections){


    return this->projections == projections;
}

bool Projections::operator!= (Projections projections){
    return !(this->projections == projections);
}
*/
int Projections::size(){
    return projections->size();
}

QStringList *Projections::getDescriptions(){
    return list_projs_names;
}
