/*****************************************************************************
 * $CAMITK_LICENCE_BEGIN$
 *
 * CamiTK - Computer Assisted Medical Intervention ToolKit
 * (c) 2001-2025 Univ. Grenoble Alpes, CNRS, Grenoble INP - UGA, TIMC, 38000 Grenoble, France
 *
 * Visit http://camitk.imag.fr for more information
 *
 * This file is part of CamiTK.
 *
 * CamiTK is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * CamiTK 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 Lesser General Public License version 3 for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with CamiTK.  If not, see <http://www.gnu.org/licenses/>.
 *
 * $CAMITK_LICENCE_END$
 ****************************************************************************/

#include <iostream>
#include <string>
using namespace std;

#include <pml/PhysicalModel.h>
#include <pml/MultiComponent.h>
#include <pml/StructuralComponent.h>
#include <pml/Atom.h>
#include <math.h>
#include <limits.h>

// -------------------- isIn ------------------------
bool isIn(StructuralComponent* sc, Atom* a) {
    unsigned int i = 0;
    bool found = false;
    while (i < sc->getNumberOfStructures() && !found) {
        found = (sc->getStructure(i) == a);
        i++;
    }
    return found;
}

// -------------------- ProgramArg ------------------------
// Code inspired from ProgVals "Thinking in C++, 2nd Edition, Volume 2", chapter 4
// by Bruce Eckel & Chuck Allison, (c) 2001 MindView, Inc.
// Available at www.BruceEckel.com.
// Program values can be changed by command lineclass ProgVals
#include <map>
#include <iostream>
#include <string>

class ProgramArg : public std::map<std::string, std::string> {
public:
    ProgramArg(std::string defaults[][2], unsigned int sz) {
        for (unsigned int i = 0; i < sz; i++) {
            insert(std::pair<const std::string, std::string&>(defaults[i][0], defaults[i][1]));
        }
    };

    void parse(int argc, char* argv[], std::string usage, int offset = 1) {
        for (int i = offset; i < argc; i++) {
            string flag(argv[i]);
            unsigned int equal = flag.find('=');
            if (equal == string::npos) {
                cerr << "Command line error: " << argv[i] << endl << usage << endl;
                continue; // Next argument
            }
            string name = flag.substr(0, equal);
            string value = flag.substr(equal + 1);
            if (find(name) == end()) {
                cerr << name << endl << usage << endl;
                continue; // Next argument
            }
            operator[](name) = value;
        }
    };

    void print(std::ostream& out = std::cout) {
        out << "Argument values:" << endl;
        for (iterator it = begin(); it != end(); ++it) {
            out << (*it).first << " = " << (*it).second << endl;
        }
    };
};

string defaultsArg[][2] = {
    { "-f", "" },
    { "-select", "" },
    { "-o", ""},
    { "-d", "comma"},
};

const char* usage = "usage:\n"
                    "pml2csv -f=file.pml [-select=name] [-o=output.csv] [-d=space]\n"
                    "(Note no space around '=')\n"
                    "Where the flags can be any of: \n"
                    "-f the input pml document\n"
                    "-select the name of the structural component or cell to export as csv\n"
                    "        (default = all atoms)\n"
                    "-o name of the csv output file (default=file.csv)\n"
                    "-d demiter can be either 'space' or 'comma' (default is 'comma')\n";

// global ProgramArgument
ProgramArg argVal(defaultsArg, sizeof defaultsArg / sizeof* defaultsArg);

// arguments
string filename;
string selected;
string output;
char separator;

// -------------------- processArg ------------------------
void processArg() {
    filename = argVal["-f"];
    output = argVal["-o"];
    selected = argVal["-select"];

    if (filename == "") {
        cerr << "Argument error: -f argument is mandatory" << endl << usage << endl;
        exit(-1);
    }

    if (output == "") {
        // generate csv output filename
        output = filename;
        unsigned int pLast = output.rfind(".");
        if (pLast != string::npos) {
            output.erase(pLast);
            output += ".csv";
        }
        else {
            output = "pml2csv-output.csv";
        }
    }

    if (argVal["-d"] == "space") {
        separator = ' ';
    }
    else {
        separator = ',';
    }

}

// -------------------- printArg ------------------------
void printArg() {
    cout << "pml2csv is converting ";
    if (selected != "") {
        cout << "component/cell " << selected;
    }
    else {
        cout << "all atoms";
    }
    cout << " of " << filename << " to CSV file " << output << " (delimiter is " << separator << ")" << endl;
}

// -------------------- main ------------------------
int main(int argc, char** argv) {
    // Initialize and parse command line values
    // before any code that uses pvals is called:
    argVal.parse(argc, argv, usage);
    //argVal.print();

    processArg();
    printArg();

    try {
        // read the pml
        cout << "-> please wait while reading " << filename;
        PhysicalModel* pm = new PhysicalModel(filename.c_str());

        // get the component
        Component* cpt = nullptr;
        Cell* cellCpt = nullptr;
        StructuralComponent* atoms = nullptr;

        cout << "-> get ";
        if (selected == "") {
            cout << "all atoms" << endl;
            atoms = pm->getAtoms();
        }
        else {
            cout << selected << endl;
            cpt = pm->getComponentByName(selected);
            if (!cpt) {
                // try harder: look for a cell
                Structure* s = pm->getStructureByName(selected);
                if (s && s->isInstanceOf("Cell")) {
                    cellCpt = (Cell*) s;
                }
                else {
                    throw PMLAbortException("No components/cells named " + selected);
                }
            }
        }

        // now extract all atoms
        StructuralComponent* selectedAtoms = new StructuralComponent(nullptr, "selected atoms");
        if (atoms) {
            for (unsigned int j = 0; j < atoms->getNumberOfStructures(); j++) {
                selectedAtoms->addStructureIfNotIn(atoms->getStructure(j));
            }
        }
        else if (cpt) {
            if (cpt->isInstanceOf("StructuralComponent") && ((StructuralComponent*)cpt)->composedBy() == StructuralComponent::CELLS) {
                for (unsigned int i = 0; i < cpt->getNumberOfCells(); i++) {
                    Cell* c = cpt->getCell(i);
                    for (unsigned int j = 0; j < c->getNumberOfStructures(); j++) {
                        selectedAtoms->addStructureIfNotIn(c->getStructure(j));
                    }
                }
            }
            else {
                StructuralComponent* sc = (StructuralComponent*)cpt;
                for (unsigned int j = 0; j < sc->getNumberOfStructures(); j++) {
                    selectedAtoms->addStructureIfNotIn(sc->getStructure(j));
                }
            }
        }
        else {
            for (unsigned int j = 0; j < cellCpt->getNumberOfStructures(); j++) {
                selectedAtoms->addStructureIfNotIn(cellCpt->getStructure(j));
            }
        }
        cout << "-> found " << selectedAtoms->getNumberOfStructures() << " atoms to export as CSV" << endl;

        // save the result
        cout << "-> please wait while saving " << output << " " << endl;
        ofstream outputFile(output.c_str());
        outputFile << "Atom#" << separator << "x" << separator << "y" << separator << "z" << endl;
        double pos[3];
        for (unsigned int i = 0; i < selectedAtoms->getNumberOfStructures(); i++) {
            Atom* a = (Atom*)selectedAtoms->getStructure(i);
            a->getPosition(pos);
            outputFile << a->getIndex() << separator << pos[0] << separator << pos[1] << separator << pos[2] << endl;
        }
        outputFile.close();

    }
    catch (const PMLAbortException& ae) {
        cout << "AbortException: Physical model aborted:" << endl ;
        cout << ae.what() << endl;
    }
}
