/*
 * 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 <QIODevice>
#include <QString>

// A known-size sequential QIODevice that frames a payload device as a single-part
// multipart/form-data body. QHttpMultiPart computes its length from the payload's
// size(), not useful for sockets.
class MultipartDevice : public QIODevice
{
    Q_OBJECT
public:
    MultipartDevice(QIODevice* payload, qint64 payload_size,
                    QString const& filename, QString const& content_type,
                    QObject* parent = nullptr);

    QByteArray content_type_header() const { return content_type_header_; }
    qint64 total_size() const;

    bool isSequential() const override { return true; }
    qint64 bytesAvailable() const override;

protected:
    qint64 readData(char* data, qint64 maxSize) override;
    qint64 writeData(char const* data, qint64 maxSize) override;

private Q_SLOTS:
    void on_payload_ready_read();
    void on_payload_read_channel_finished();

private:
    QIODevice* const payload_;
    qint64 const payload_size_;
    QByteArray content_type_header_;
    QByteArray prologue_;
    QByteArray epilogue_;

    // Segment offsets
    qint64 payload_begin_ = 0;
    qint64 epilogue_begin_ = 0;
    qint64 pos_ = 0;
    bool payload_finished_ = false;
};
