/*
*  main.cpp
*  QUIMUP main program file
*  © 2008-2024 Johan Spee
*  SPDX-License-Identifier: GPL-3.0-or-later
*/

#include <QTranslator>
#include <QLibraryInfo>
#include <QLocale>
#include <QStringConverter>
#include <QDir>
#include <QApplication>
#include "QtSingleApplication/qtsingleapplication.h"
#include "qm_core.h"
#include "qm_config.h"

// snippet:
// QString mystring("some string");
// printf("%s\n", mystring.toStdString().c_str());

int main(int argc, char **argv)
{
    /*  SET VERSION HERE
        implented below     */
    QString release_version = "2.1.1";

    QtSingleApplication app("QUIMUP", argc, argv);
    bool b_multiple_instances = false;
    QString locale = "none";
    int filecount = 0;
    bool b_extensive = false;

    QStringList args_for_main;

    for (int a = 1; a < argc; ++a)
    {
        QByteArray arg = argv[a];

        if ( arg == "-i" || arg == "-instance")
        {
            b_multiple_instances = true;
        }
        else
        if ( arg == "-l"  || arg == "-locale" )
        {
            if (a < (argc-1) )
            {
                locale = argv[a+1];
                // possible stray '-l'
                if ( locale.startsWith("-") || locale.startsWith("file") )
                    locale = "xx";
                else
                    a++;
            }
        }
        else
        if (arg == "-e" || arg == "-extensive")
        {
            b_extensive = true;
        }
        if (arg == "-h" || arg == "-help")
        {
            printf ("----\nQuimup version %s\n", release_version.toUtf8().data()); // VERSION //
            printf ("© 2008-2024 Johan Spee <oubliette@xs4all.nl>\n");
            printf ("This program is licensed by the GPL and distributed in the hope that it will be useful, but without any warranty\n");
            printf ("----\ncommand line parameters:\n");
            printf (" -h(elp)           show this information and exit\n");
            printf (" -e(xtensive)      show more detailed information on errors\n");
            printf (" -i(nstance)       force a new instance of Quimup\n");
            printf (" -l(ocale) xx      use locale 'xx' (fr, po, en_GB, etc) or 'none' to force default locale\n");
            printf (" -l(ocale) file    use locale from full path to quimup_xx.qm file\n");
            printf (" -p(lay) %%U        play files in %%U (or %%F) in new playlist\n");
            printf ("  %%U               append files in %%U (or %%F) to the playlist\n----\n");
            return 0;
        }
        else
        if ( arg == "-p" || arg == "-play")
        {
            args_for_main.push_back("-play");
        }
        else // URL
        if ( arg.startsWith("file://"))
        {
            args_for_main.push_back(arg);
            filecount++;
        }
        else // Plain path, starting with /
        if ( arg.startsWith("/") )
        {
            args_for_main.push_back(arg);
            filecount++;
        }
    }

    QString message;
    if (filecount == 0)
        message = "wakeupcall";
    else
        message = args_for_main.join("*!#!*").toUtf8();
    // nb. splitter "*!#!*" is added here and removed in core

    // if app.sendMessage returns true there already is an instance
    if (!b_multiple_instances && app.sendMessage(message))
    {
        printf ("Quimup : already running (use '-i' to force a new instance)\n");
        return 0;
    }

    printf ("Quimup: starting new instance\n");

    // Set version, b_extensive and this_is_wayland
    qm_Config *config = new qm_Config(b_extensive);

    if (config != nullptr)
    {
        if (config->version != release_version)
        {
            printf ("Updating release version in config\n");
            config->version = release_version; 
        }

        config->cout_extensive = b_extensive;
        config->this_is_wayland = (QGuiApplication::platformName() == "wayland");

        config->save_config();
    }
    else
    {
        printf ("!! Failed to open or create quimup.conf\n");
        printf ("!! Terminating :(\n");
        return 0;
    }


    // >> Localization START >
    // This is a work in progress. Not tested.
    QTranslator trnsltr;

    bool b_locale_loaded = false;
    bool b_locale_default = true;
    if (locale == "xx") // -l xx parameter was passed
        locale = QLocale::system().name();
    else
        b_locale_default = false;

    if (locale != "none")
    {
        if (!b_locale_default)
        {
            printf ("Locale: '%s': ", static_cast<const char*>(locale.toUtf8()));
            if ( locale.startsWith("/") && locale.endsWith(".qm")) // full path to a file
            {
                if ( trnsltr.load(locale) )
                {
                   printf ("OK\n");
                   b_locale_loaded = true;
                }
                else
                   printf ("failed! (using none)\n");
            }
            else // first try installation path, next default path
            {
                QDir dir(QApplication::applicationDirPath());

                if ( trnsltr.load(QString("quimup_") + locale, dir.absolutePath()) )
                {
                    printf ("OK (from %s)\n", static_cast<const char*>(dir.absolutePath().toUtf8()));
                    b_locale_loaded = true;
                }
                else
                {
                    if ( trnsltr.load(QString("quimup_") + locale, QLibraryInfo::path(QLibraryInfo::TranslationsPath)) )
                    {
                        printf ("OK (from default location)\n");
                        b_locale_loaded = true;
                    }
                    else
                         printf ("failed! (using none)\n");
                }
            }

        }
        else // locale file in default system location
        {
            printf ("Locale: ");
            if ( trnsltr.load(QString("quimup_") + locale, QLibraryInfo::path(QLibraryInfo::TranslationsPath)) )
            {
                printf ("using default (%s)\n", static_cast<const char*>(locale.toUtf8()));
                b_locale_loaded = true;
            }
            else
                printf ("using none\n");
        }
    }
    else
    {
        if (b_extensive)
            printf ("Locale: none requested\n");
    }

    if (b_locale_loaded)
        app.installTranslator(&trnsltr);
    // << END Localization

    qm_Core *core = new qm_Core(config);

    QObject::connect( &app, SIGNAL(messageReceived(const QString&)),
                     core, SLOT(on_message_from_main(const QString&)) );


    if (filecount > 0)
    // 1st instance: we send the arguments directly
        core->on_message_from_main(message);


    // when this is terminated make the core clean up
    QObject::connect( &app, SIGNAL(aboutToQuit()), core, SLOT(on_system_quit()) );

    return app.exec();
}
