/***
   This file is part of fly-ocr.

   Copyright (C) 2021 LLC "RusBITech-Astra" (https://astralinux.ru)

   Foobar 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.

   Foobar 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 fly-ocr. If not, see <https://www.gnu.org/licenses/>.
***/

#include <QtSingleApplication>
#include <QMessageBox>
#include <QFileInfo>
#include <QDir>
#include <fly-ocr/ocrengine.h>
#include <iostream>
#include <unistd.h>
#include "mainwindow.h"
#include "sourcemanager.h"
#include "recognizer.h"
#include "flyocrstarter.h"

FlyOcrStarter::FlyOcrStarter(QtSingleApplication* app) : QObject(app)
{
    m_parser.addPositionalArgument("file", tr("Image file path"));
    m_parser.addOption(m_quitOption);
    m_parser.addOption(m_raiseOption);
    m_parser.addOption(m_ocrOption);
    m_parser.addOption(m_statusOption);

    QCommandLineOption versionOption = m_parser.addVersionOption();
    QCommandLineOption helpOption = m_parser.addHelpOption();
    m_parser.process(app->arguments());

    if (m_parser.isSet(helpOption) || m_parser.isSet(versionOption)) {
        m_finished = true;
        return;
    }

    if (m_parser.isSet(m_statusOption)) {
        std::cout << app->isRunning() << std::endl;
        m_finished = true;
        return;
    }

    QStringList args = app->arguments();

    if (app->isRunning()) {
        args.append(QDir::currentPath()); //last argument is the current working dir
        app->sendMessage(args.join("|||"));
        m_finished = true;
        return;
    }

    connect(app, &QtSingleApplication::messageReceived, this, &FlyOcrStarter::onMessageReceived);

    OcrEngine::loadPlugins();
    m_mw = new MainWindow;
    m_mw->show();
    processCommands(QDir::currentPath());
}

FlyOcrStarter::~FlyOcrStarter()
{
    if (m_mw)
        delete m_mw;
}

bool FlyOcrStarter::isFinished() const
{
    return m_finished;
}

int FlyOcrStarter::exitCode() const
{
    return m_exitCode;
}

void FlyOcrStarter::onMessageReceived(const QString& message)
{
    QStringList args = message.split("|||");
    if (args.isEmpty())
        return;

    if (args.count() == 2) { //executable path and current working dir (i.e. application was started without arguments)
        m_mw->show();
        m_mw->raise();
        m_mw->activateWindow();
        return;
    }

    QString currentWorkingDir = args.takeLast();
    m_parser.process(args);
    if (m_parser.isSet(m_raiseOption)) {
        m_mw->show();
        m_mw->raise();
        m_mw->activateWindow();
    }
    processCommands(currentWorkingDir);
}

void FlyOcrStarter::processCommands(const QString& currentWorkingDir)
{
    if (m_parser.isSet(m_raiseOption))
        return;

    if (!m_parser.positionalArguments().isEmpty()) {
        QStringList fullPathList;
        for (const QString& s : m_parser.positionalArguments()) {
            if (QFileInfo(s).isAbsolute()) //absolute path
                fullPathList << s;
            else //relative path
                fullPathList << QFileInfo(currentWorkingDir + "/" + s).canonicalFilePath();
        }

        m_mw->sourceManager()->add(fullPathList);

        if (m_parser.isSet(m_ocrOption))
            m_mw->recognizer()->enqueueFiles(fullPathList);
    } else if (m_parser.isSet(m_quitOption)) {
        qApp->closeAllWindows();
        qApp->quit();
    }
}
