/*
    SPDX-FileCopyrightText: 2022 Friedrich W. H. Kossebau <kossebau@kde.org>

    SPDX-License-Identifier: LGPL-2.1-or-later
*/

#include "readimagefilerunner.hpp"

// own
#include "imagereadresult.hpp"
#include "imagereadresult_p.hpp"
// Qt
#include <QFile>
#include <QImageReader>

namespace Kodaskanna
{

namespace ImageSource
{

ReadImageFileRunner::ReadImageFileRunner(const QString &localFileName)
    : m_localFileName(localFileName)
{
}

void ReadImageFileRunner::run()
{
    bool isOpened;
    QFile input;
    if (m_localFileName.isEmpty()) {
        isOpened = input.open(stdin, QIODevice::ReadOnly | QIODevice::Unbuffered);
    } else {
        input.setFileName(m_localFileName);
        isOpened = input.open(QIODevice::ReadOnly);
    }

    auto *resultData = new ImageReadResultPrivate;
    ImageReadResult imageReadResult(resultData);

    if (isOpened) {
        QImageReader reader(&input);
        reader.setAutoTransform(true);
        const QImage loadedImage = reader.read();

        resultData->isSuccess = !loadedImage.isNull();
        if (resultData->isSuccess) {
            resultData->image = loadedImage;
        }
    } else {
        resultData->isSuccess = false;
    }

    // TODO: add error message if no success
    Q_EMIT readFinished(imageReadResult);
}

}
}

#include "moc_readimagefilerunner.cpp"
