/*
 * Copyright (C) 2016 Canonical Ltd.
 * Copyright (C) 2026 UBports Foundation.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#pragma once

#include <QLocalSocket>
#include <QNetworkReply>
#include <QObject>
#include <lomiri/storage/provider/Item.h>
#include <lomiri/storage/provider/UploadJob.h>

#include <cstdint>
#include <memory>
#include <string>

class MultipartDevice;
class RcloneClient;

class RcloneUploadJob : public QObject, public lomiri::storage::provider::UploadJob
{
    Q_OBJECT
public:
    RcloneUploadJob(std::shared_ptr<RcloneClient> const& client,
                    std::string const& fs, std::string const& item_id,
                    int64_t size, std::string const& content_type,
                    bool allow_overwrite, std::string const& old_etag);
    ~RcloneUploadJob();

    boost::future<void> cancel() override;
    boost::future<lomiri::storage::provider::Item> finish() override;

private Q_SLOTS:
    void onReplyFinished();

private:
    void start_upload();
    void set_exception(boost::exception_ptr const& error);

    std::shared_ptr<RcloneClient> const client_;
    std::string const fs_;
    std::string const item_id_;
    int64_t const size_;
    std::string const content_type_;
    bool const allow_overwrite_;
    std::string const old_etag_;

    QLocalSocket reader_;
    std::unique_ptr<MultipartDevice> multipart_;
    std::unique_ptr<QNetworkReply> reply_;

    std::shared_ptr<bool> const alive_ = std::make_shared<bool>(true);

    bool cancelled_ = false;
    bool promise_set_ = false;
    std::shared_ptr<boost::promise<lomiri::storage::provider::Item>> promise_ =
        std::make_shared<boost::promise<lomiri::storage::provider::Item>>();
};
