/*
 * 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 <QObject>
#include <QProcess>
#include <QString>
#include <QTimer>
#include <QUrl>

#include <boost/exception_ptr.hpp>

// Manages the lifecycle of a child "rclone rcd" remote-control daemon.
class RcloneDaemon : public QObject
{
    Q_OBJECT
public:
    enum class State { Starting, Ready, Failed };

    explicit RcloneDaemon(QObject* parent = nullptr);
    ~RcloneDaemon();

    State state() const { return state_; }
    QString error_string() const { return error_; }

    QUrl base_url() const { return base_url_; } // http://127.0.0.1:<port>/
    QString user() const { return user_; }
    QString password() const { return password_; }

    // For client to set once rc/noop test succeeded/failed
    void set_ready();
    void set_failed(QString const& reason);
    void set_failed(boost::exception_ptr const& error);

Q_SIGNALS:
    void listening();   // TCP connection accepted
    void ready();       // rc/noop succeeded
    void failed(QString const& reason);

private Q_SLOTS:
    void poll_port();
    void on_process_error(QProcess::ProcessError error);
    void on_process_finished(int exit_code, QProcess::ExitStatus status);

private:
    QProcess process_;
    int port_ = 0;
    QString const user_;
    QString password_;
    QUrl base_url_;
    State state_ = State::Starting;
    QString error_;

    QTimer poll_timer_;
    QTimer deadline_timer_;
    bool listening_emitted_ = false;
};
