#ifndef WORKER_H
#define WORKER_H

#include <string>
#include <vector>
#include <thread>
#include <mutex>
#include <atomic>
#include <iostream>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>
#include <cstdlib>
#include <memory>

/////////////////////////////////////////////////////////////////////////////

#include "interface.h"

/////////////////////////////////////////////////////////////////////////////

class Worker {
public:
    Worker(Front* front);
    ~Worker();
    bool startServer(int port);
    void stopServer();
    void handleViewLogCommand(const std::string& command, int clientFD);
    void printLedgerinshell(const terminal_dev& dev, int fd);
    void ledger(const std::string& terminal_id, int fd);
    void value_print(const std::string& variableName, int clientFD);
    void sendStr(int fd, const std::string& s);
    void printPrompt(int clientFD);

private:
    Front* m_front;
    
    std::mutex testMutex;
    int listenFD;
    std::atomic<bool> running;
    std::thread serverThread;
    std::vector<std::string> commandHistory;
    int historyIndex;
    std::string currentCommand;
    bool stopViewLog;
    bool g_stopTelnetTest;
    static constexpr unsigned char IAC = 255;
    static constexpr unsigned char WILL = 251;
    static constexpr unsigned char WONT = 252;
    static constexpr unsigned char TELDO = 253;
    static constexpr unsigned char DONT = 254;
    static constexpr unsigned char TELOPT_ECHO = 1;
    static constexpr unsigned char TELOPT_SUPPRESS_GO_AHEAD = 3;
    static constexpr unsigned char TELOPT_LINEMODE = 34;

    void acceptLoop();
    void sessionThread(int clientFD);
    void sendTelnetNegotiation(int clientFD);
    void sendBytes(int fd, const char* buf, int len);
    void setTestNum(int num);
    void setTestType(int type);
    void setTestlog(bool flag);
    void doPeriodicTask();
    void processCommand(const std::string &cmd, int clientFD);
    void handleUpArrow(int fd);
    void handleDownArrow(int fd);
    std::string trim(const std::string& s);
};

#endif // WORKER_H