// XDrawChem
// Copyright (C) 2004-2005  Bryan Herger <bherger@users.sourceforge.net>
// Copyright (C) 2020  Yaman Qalieh <ybq987@gmail.com>

// 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 <https://www.gnu.org/licenses/>.

#include <QApplication>
#include <QLocale>
#include <QString>
#include <QTextStream>
#include <QTimer>
#include <QTranslator>

#include "application.h"
#include "clipboard.h"
#include "defs.h"
#include "dyk.h"
#include "prefs.h"

QString RingDir, HomeDir;
QTextStream out(stdout);
Preferences preferences;

void usage(); // defined below

int main(int argc, char **argv) {
    int ae;

    // parse command line options
    QStringList cmds;
    QString infile, outfile;
    bool loadflag = false, pngflag = false, quitflag = false, helpflag = false, versionflag = false,
         tflag = false, to3dflag = false;

    for (int c1 = 0; c1 < argc; c1++) {
        cmds.append(argv[c1]);
    }
    if (cmds.count() > 1) {
        foreach (QString arg, cmds) {
            qDebug() << arg << ":";
            if (arg == "-h") {
                helpflag = true;
                continue;
            }
            if (arg == "--help") {
                helpflag = true;
                continue;
            }
            if (arg == "-v") {
                versionflag = true;
                continue;
            }
            if (arg == "--version") {
                versionflag = true;
                continue;
            }
            if (arg == "-t") {
                tflag = true;
                continue;
            }
            if (arg == "-png") {
                pngflag = true;
                outfile = arg;
                continue;
            }
            if (arg == "-3d") {
                to3dflag = true;
                outfile = arg;
                continue;
            }
            loadflag = true;
            infile = arg;
        }
    }

    if (helpflag)
        usage();
    if (versionflag) {
        out << XDC_VERSION << Qt::endl;
        exit(0);
    }

    QApplication a(argc, argv);

    // set library directory (RingDir = default RINGHOME)
    QString dname(RINGHOME);
    if (dname.right(1) != QString("/"))
        dname.append(QString("/"));
    // dname.append( "ring/" );

    qInfo() << "appDirPath::" << QApplication::applicationDirPath();
    QString altdname = QApplication::applicationDirPath();
    if (altdname.contains("Contents/MacOS")) {
        dname = altdname.replace("Contents/MacOS", "Contents/Resources");
        if (dname.right(1) != QString("/"))
            dname.append(QString("/"));
    }
    if (altdname.contains("Program Files")) {
        dname = altdname;
        if (dname.right(1) != QString("/"))
            dname.append(QString("/"));
        dname.append("ring/");
    }
    qInfo() << "dname = " << dname;
    RingDir = QApplication::applicationDirPath().replace("bin", "ring/");

    // set home directory/pref file and fallback dir/pref file
#ifdef UNIX
    HomeDir = getenv("HOME");
    QString cRingDir = HomeDir;

    cRingDir.append("/.xdrawchem/");
    preferences.setCustomRingDir(cRingDir);
    HomeDir = HomeDir + "/.xdrawchemrc";
    preferences.setSaveFile(HomeDir);
    QFile f1(HomeDir);

    if (f1.open(QIODevice::ReadOnly) == false) {
        HomeDir = RingDir + "xdrawchemrc";
        preferences.setFile(HomeDir, true);
    } else {
        f1.close();
        preferences.setFile(HomeDir, false);
    }
#else // Windows, Mac?
    HomeDir = "xdrawchemrc";
    preferences.setCustomRingDir(RingDir);
    preferences.setSaveFile(HomeDir);
    QFile f1(HomeDir);

    if (f1.open(QIODevice::ReadOnly) == false) {
        HomeDir = RingDir + "xdrawchemrc";
        preferences.setFile(HomeDir, true);
    } else {
        f1.close();
        preferences.setFile(HomeDir, false);
    }
#endif

    if (preferences.LoadPrefs() == false) {
        qWarning() << "Unable to load preferences file";
        preferences.Defaults();
    }
    // translation file for application strings
    QTranslator translator;

    translator.load(QString::fromLatin1("xdrawchem_") + QLocale::system().name(), RingDir);
    a.installTranslator(&translator);

    ApplicationWindow *mw = new ApplicationWindow;

    mw->setWindowTitle(QString(XDC_VERSION) + QString(" - ") + mw->tr("untitled"));
    if (loadflag)
        mw->load(infile);
    mw->show();
    if (pngflag) {
        mw->ni_savefile = outfile;
        mw->ni_tflag = tflag;
        QTimer::singleShot(0, mw, SLOT(savePNG()));
    }
    if (to3dflag) {
        mw->ni_savefile = outfile;
        mw->ni_tflag = tflag;
        QTimer::singleShot(0, mw, SLOT(save3D()));
    }

    if (quitflag)
        exit(0); // exit if non-interactive mode.

    a.connect(&a, SIGNAL(lastWindowClosed()), &a, SLOT(quit()));
    mw->HideTextButtons();

    if (preferences.getDYK()) {
        DYKDialog dyk1;

        dyk1.exec();
    }

    ae = a.exec();
    if (preferences.SavePrefs() == false) {
        qWarning() << "Unable to save preferences file";
    }
    return ae;
}

void usage() {
    out << XDC_VERSION << Qt::endl;
    out << "Usage:" << Qt::endl;
    out << "  xdrawchem [input file] [options]" << Qt::endl;
    out << "Command line options:" << Qt::endl;
    out << "-png <output file>: Create a PNG image of input file and exit" << Qt::endl;
    out << "-t: Make transparent PNG (also specify -png)" << Qt::endl;
    out << "-3d: Make 3D model of input file (output MDL mofile)" << Qt::endl;
    out << "-h, --help:  Display this help" << Qt::endl;
    out << "-v, --version:  Display the version information" << Qt::endl;

    exit(0);
}
