/* common/KMInputStream.h
 *
 * Copyright (C) 2023 OpenKylin, Inc
 */

#include "KMInputStream.h"

#include <iostream>

class KMInputStream::Private
{
public:
    Private(GInputStream* inputStream);
    ~Private();

    GInputStream* m_inputStream = nullptr;
};

KMInputStream::Private::Private(GInputStream* inputStream)
{
    m_inputStream = inputStream;
}

KMInputStream::Private::~Private()
{
    if (m_inputStream)
    {
        g_object_unref(m_inputStream);
    }
}

KMInputStream::KMInputStream()
{}

KMInputStream::KMInputStream(KMFile& file)
{
    g_autoptr(GError) error = NULL;

    GInputStream * rawInput = (GInputStream *)g_file_read(file.get(), nullptr, &error);
    if (error)
    {
        std::cerr << error->message << std::endl;
    }

    if (rawInput)
    {
        d = std::make_shared<Private>(rawInput);
    }
}

KMInputStream::KMInputStream(GInputStream* input)
{
    if (input)
    {
        d = std::make_shared<Private>(input);
    }
}

KMInputStream::~KMInputStream()
{}

// 不进行深拷贝
KMInputStream& KMInputStream::operator=(const KMInputStream& other)
{
    if (this != &other && d->m_inputStream != other.d->m_inputStream)
    {
        d = other.d;
    }

    return *this;
}

KMInputStream& KMInputStream::operator=(GInputStream* input)
{
    if (input)
    {
        if (d)
        {
            if (d->m_inputStream == input)
            {
                // do nothing
            }
            else if (d->m_inputStream)
            {
                g_object_unref(d->m_inputStream);
                d->m_inputStream = input;
            }
        }
        else
        {
            d = std::make_shared<Private>(input);
        }
    }
    else
    {
        d.reset();
    }

    return *this;
}

GInputStream* KMInputStream::get()
{
    if (d)
    {
        return d->m_inputStream;
    }
    else
    {
        return nullptr;
    }
}

