#pragma once

#include "../TradeCore/message.hh"
#include <QTableWidget>
#include <QLocalServer>
#include <QLocalSocket>
#include <QTimer>
#include <memory>

class Connection;
using ConnectionPtr = std::shared_ptr<Connection>;

constexpr char serverName[] = "AutoTrader";

/**
 * @brief Server class handles and stores new connections
 * It is also a table widget that displays opened connections.
 */
class ServerWidget : public QTableWidget
{
    Q_OBJECT

public:
    explicit ServerWidget(QWidget* parent = nullptr);
    bool listen();
    void disconnectAll();
    bool closeConnection(int clientId);
    bool isRegistered(int clientId);

public slots:
    void sendMessage(const Message& message);

signals:
    void newConnectionCreated();
    void connectionRegistered(int, const Registration&);
    void messageReceived(const Message&);
    void connectionClosed(int);

private slots:
    void handleNewConnection();
    void onConnectionRegistered(int clientId, const Registration& registration);
    void onDisconect();
    void onCellDoubleClicked(int row, int);
    void onTimerTimeout();

private:
    std::vector<ConnectionPtr> connections_;
    QLocalServer server_;
    QTimer timer_;
};
