#pragma once

#include "../shared/protocol/message.h"
#include "config/client_config.h"
#include "media/video_decoder.h"
#include <boost/asio.hpp>
#include <boost/asio/ssl.hpp>
#include <QObject>
#include <QImage>
#include <memory>
#include <atomic>
#include <chrono>

namespace scar {

class ClientConnection : public QObject {
    Q_OBJECT

public:
    explicit ClientConnection(QObject* parent = nullptr);
    ~ClientConnection();
    
    // Connect to server
    void connectToServer(const std::string& host, uint16_t port,
                        const std::string& username, const std::string& password);
    
    // Disconnect from server
    void disconnect();
    
    // Send messages
    void sendTextMessage(const std::string& content);
    void sendData(const std::vector<uint8_t>& data);
    
    // Check connection status
    bool isConnected() const { return connected_; }
    
signals:
    void connected();
    void disconnected();
    void loginSuccess(const QString& token);
    void loginFailed(const QString& error);
    void messageReceived(const QString& sender, const QString& content);
    void connectionError(const QString& error);
    void screenShareFrameReceived(std::vector<uint8_t> rgbData, int width, int height);

private:
    void doConnect(const std::string& host, uint16_t port);
    void doHandshake();
    void doLogin(const std::string& username, const std::string& password);
    void doReadHeader();
    void doReadBody(uint32_t length);
    void handleMessage(std::unique_ptr<Message> message);
    void scheduleReconnect();
    void runIoContext();
    
    std::unique_ptr<boost::asio::io_context> io_context_;
    std::unique_ptr<boost::asio::ssl::context> ssl_context_;
    std::unique_ptr<boost::asio::ssl::stream<boost::asio::ip::tcp::socket>> socket_;
    std::unique_ptr<boost::asio::executor_work_guard<boost::asio::io_context::executor_type>> work_guard_;
    
    std::vector<uint8_t> read_buffer_;
    std::atomic<bool> connected_;
    std::atomic<bool> should_reconnect_;
    
    // Video decoder for screen shares
    std::unique_ptr<VideoDecoder> screen_share_decoder_;
    
    // Reconnection backoff
    int reconnect_attempts_;
    std::chrono::seconds backoff_delay_;
    std::string last_host_;
    uint16_t last_port_;
    std::string last_username_;
    std::string last_password_;
    
    static constexpr int MAX_RECONNECT_ATTEMPTS = 10;
    static constexpr int INITIAL_BACKOFF_SECONDS = 1;
    static constexpr int MAX_BACKOFF_SECONDS = 60;
};

} // namespace scar
