/*
 * Copyright © 2013 Canonical Ltd.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * 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 Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Authored by: Thomas Voß <thomas.voss@canonical.com>
 */

#include <com/lomiri/content/transfer.h>

#include "transfer_p.h"
#include "utils.cpp"

namespace cuc = com::lomiri::content;

cuc::Transfer::Transfer(const QSharedPointer<cuc::Transfer::Private>& d, QObject* parent)
        : QObject(parent),
          d(d)
{
    QObject::connect(d->remote_transfer,
                SIGNAL (StateChanged(int)),
                this,
                SIGNAL (stateChanged()));
    QObject::connect(d->remote_transfer,
                SIGNAL (StoreChanged()),
                this,
                SIGNAL (storeChanged()));
    QObject::connect(d->remote_transfer,
                SIGNAL (SelectionTypeChanged(int)),
                this,
                SIGNAL (selectionTypeChanged()));
}

cuc::Transfer::~Transfer()
{
    TRACE() << Q_FUNC_INFO;

    auto s = store();
    if (s.scope() == Scope::transient)
        purge_store_cache(s.uri());
}

int cuc::Transfer::id() const
{
    return d->id();
}

cuc::Transfer::State cuc::Transfer::state() const
{
    return d->state();
}

bool cuc::Transfer::start()
{
    return d->start();
}

bool cuc::Transfer::abort()
{
    return d->abort();
}

bool cuc::Transfer::charge(const QVector<cuc::Item>& items)
{
    return d->charge(items);
}

QVector<cuc::Item> cuc::Transfer::collect()
{
    return d->collect();
}

bool cuc::Transfer::finalize()
{
    return d->finalize();
}

cuc::Store cuc::Transfer::store() const
{
    auto result = d->store();

    return cuc::Store{
        static_cast<Scope>(std::get<0>(result)),
        Type(std::get<1>(result)),
        std::get<2>(result)
    };
}

bool cuc::Transfer::setStore(const cuc::Store* store)
{
    if (store->scope() == Scope::unknown) {
        /*
         * This means old code has created a Store object directly from path.
         * Returning `false` should tell the caller that it will not have the
         * requested store on the transfer, but in practice people seem to not
         * check this function's return code.
         *
         * To prevent surprise later on, let's pretend that the transfer has
         * been aborted due to error.
         */
        abort();
        return false;
    }

    auto store_path = d->setStore(store->scope(), store->type().id());

    if (store_path.isNull())
        return false;

    /* If needed and possible, create or migrate the store to where the application expects. */
    if (store->uri() == store_path)
        return true;

    if (not QFile::exists(store->uri())) {
        // :shrug:️
        return true;
    }

    if (QFile::symLinkTarget(store->uri()) == store_path) {
        /* Probably the migration has already happened. */
        return true;
    }

    QDir store_dir(store_path);
    if (store_dir.exists()) {
        if (not store_dir.isEmpty()) {
            /* We have to merge the content of dirs, which I reckon isn't worth
             * coding up. But return true nonetheless since the migration is best-effort. */
            return true;
        }

        store_dir.removeRecursively();
    }

    QFile::rename(store->uri(), store_path);

    /* Create absolute path, because :shrug:. Don't check the error, as if
     * application can't create the symlink, there shouldn't be any content
     * in it anyway. */
    QFile::link(store_path, store->uri());

    return true;
}

/*!
 * \returns the new store path as seen by the service, or a null QString().
 */
QString cuc::Transfer::setStore(Scope scope, const QString & type)
{
    return d->setStore(scope, type);
}

cuc::Transfer::SelectionType cuc::Transfer::selectionType() const
{
    return d->selection_type();
}

bool cuc::Transfer::setSelectionType(const cuc::Transfer::SelectionType& type)
{
    return d->setSelectionType(type);
}

cuc::Transfer::Direction cuc::Transfer::direction() const
{
    return d->direction();
}

QString cuc::Transfer::downloadId() const
{
    return d->downloadId();
} 

bool cuc::Transfer::setDownloadId(QString downloadId)
{
    return d->setDownloadId(downloadId);
}

bool cuc::Transfer::download()
{
    return d->download();
}

QString cuc::Transfer::contentType() const
{
    return d->contentType();
}

QString cuc::Transfer::source() const
{
    return d->source();
}

QString cuc::Transfer::destination() const
{
    return d->destination();
}
