/*
 * 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 <QByteArray>
#include <QLocalSocket>
#include <QNetworkReply>
#include <QObject>
#include <lomiri/storage/provider/DownloadJob.h>
#include <lomiri/storage/provider/Exceptions.h>

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

class RcloneClient;

class RcloneDownloadJob : public QObject, public lomiri::storage::provider::DownloadJob
{
    Q_OBJECT
public:
    RcloneDownloadJob(std::shared_ptr<RcloneClient> const& client,
                      std::string const& fs, std::string const& item_id,
                      std::string const& match_etag);
    ~RcloneDownloadJob();

    boost::future<void> cancel() override;
    boost::future<void> finish() override;

private Q_SLOTS:
    void onReplyFinished();
    void onReplyReadyRead();
    void onReplyReadChannelFinished();
    void onSocketBytesWritten(int64_t bytes);

private:
    void start_download();
    void maybe_send_chunk();
    void handle_error(lomiri::storage::provider::StorageException const& exc);
    void handle_error(std::exception_ptr ep);
    void checkStatus();

    std::shared_ptr<RcloneClient> const client_;
    std::string const fs_;
    std::string const item_id_;
    std::string const match_etag_;

    QLocalSocket writer_;
    std::unique_ptr<QNetworkReply> reply_;

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

    bool cancelled_ = false;
    bool seen_status_ = false;
    bool read_channel_finished_ = false;
    int64_t bytes_read_ = 0;
    int64_t bytes_written_ = 0;

    bool is_error_ = false;
    QByteArray error_body_;
};
