/*****************************************************************************
 * $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/StructuralComponent.h>
#include <pml/MultiComponent.h>

// the input .obj file
PhysicalModel* pm;
string pmlFile;
string outputBase;

// -------------------- 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", "none" },
    { "-o", "pml2ansys-output" },
};

const char* usage = "usage:\n"
                    "pml2ansys -f=document.pml [-o=output]\n"
                    "Transform a PML document containing an 'Elements' exclusive structural component to a .node and .elem (readable in ANSYS)\n"
                    "(Note no space around '=')\n"
                    "Where the flags can be any of: \n"
                    "f (input pml document), o (output base file name) \n";

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

// -------------------- processArg ------------------------
void processArg() {
    pmlFile = argVal["-f"];
    outputBase = argVal["-o"];
    if (pmlFile == "none") {
        cerr << "Argument error: -f is mandatory" << usage << endl;
        exit(-1);
    }
}

// -------------------- printArg ------------------------
void printArg() {
    cout << "pml2ansys generating " << outputBase << ".elem and " << outputBase << ".node from " << pmlFile << endl;
    cout << 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 {
        pm = new PhysicalModel(pmlFile.c_str());

        //-- create the .node
        // open the node file for writing
        string nodeFile = outputBase + ".node";
        string nodeFileTxt = outputBase + "-node.txt";
        std::ofstream nodeStream;
        nodeStream.open(nodeFile.c_str());
        if (!nodeStream.is_open()) {
            cerr << "Error: cannot open file " << nodeFile << endl;
            exit(1);
        }
        std::ofstream nodeStreamTxt;
        nodeStreamTxt.open(nodeFileTxt.c_str());
        if (!nodeStreamTxt.is_open()) {
            cerr << "Error: cannot open file " << nodeFileTxt << endl;
            exit(1);
        }

        StructuralComponent* sc = pm->getAtoms();
        Atom* a;
        double pos[3];
        nodeStream.setf(ios::fixed, ios::floatfield); // set fixed floating format
        nodeStream.precision(12);
        nodeStreamTxt.setf(ios::fixed, ios::floatfield); // set fixed floating format
        nodeStreamTxt.precision(12);
        for (unsigned int i = 0; i < sc->getNumberOfStructures(); i++) {
            a = (Atom*) sc->getStructure(i);
            a->getPosition(pos);
            nodeStream << a->getIndex() + 1 << " " << pos[0] << " " << pos[1] << " " << pos[2] << endl; //<< " 0 0 0" << endl;
            nodeStreamTxt << "n," << a->getIndex() + 1 << "," << pos[0] << "," << pos[1] << "," << pos[2] << endl; //<< " 0 0 0" << endl;
        }

        nodeStream.close();
        nodeStreamTxt.close();

        //-- create the .elem
        // find the structural component "Elements" in the exclusive components
        Component* cpt = pm->getComponentByName("Elements");
        if (!cpt) {
            cout << "Cannot find any component named \"Elements\". Exiting" << endl;
            exit(-1);
        }

        // check if it is a correct one
        if (!cpt->isExclusive() || !cpt->isInstanceOf("StructuralComponent")) {
            cout << "Cannot translate the \"Elements\" component: not exclusive or not a structural component. Exiting" << endl;
            exit(-2);
        }

        // check if c is made of hexahedron
        sc = (StructuralComponent*) cpt;
        if (sc->composedBy() != StructuralComponent::CELLS || sc->getNumberOfStructures() == 0 || (sc->getCell(0)->getType() != StructureProperties::HEXAHEDRON)) {
            cout << "Cannot translate the \"Elements\" component: does not contains any cell geometric type HEXAHEDRON. Exiting" << endl;
            exit(-3);
        }

        // open the elem file for writing
        string elemFile = outputBase + ".elem";
        std::ofstream elemStream;
        elemStream.open(elemFile.c_str());
        if (!elemStream.is_open()) {
            cerr << "Error: cannot open file " << elemFile << endl;
            exit(1);
        }

        // now, we have the right component, let's do some work...
        Cell* c;
        for (unsigned int i = 0; i < sc->getNumberOfStructures(); i++) {
            c = (Cell*) sc->getCell(i);
            if (c->getType() == StructureProperties::HEXAHEDRON) {
                elemStream  << c->getStructure(0)->getIndex() + 1 << " "
                            << c->getStructure(1)->getIndex() + 1 << " "
                            << c->getStructure(2)->getIndex() + 1 << " "
                            << c->getStructure(3)->getIndex() + 1 << " "
                            << c->getStructure(4)->getIndex() + 1 << " "
                            << c->getStructure(5)->getIndex() + 1 << " "
                            << c->getStructure(6)->getIndex() + 1 << " "
                            << c->getStructure(7)->getIndex() + 1 << " "
                            " 1 1 0 0 0 0" << endl;
            }
        }

        elemStream.close();

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