#include "qshell_telnet.hpp"

TelnetQShell::TelnetQShell()
: inherited(&telnet_io)
, _port()
, telnet_io(&_port)
{}

TelnetQShell::TelnetQShell(portid port, shell_t::const_cmd shell_name, QObject *parent)
: inherited(&telnet_io, shell_name, parent)
, _port(port)
, telnet_io(&_port)
{
    connect( this, &QShell::finished, this, &TelnetQShell::close );
}

TelnetQShell::TelnetQShell(portid port
        , const std::string& shell_name
        , QObject *parent)
: inherited(&telnet_io, shell_name.c_str(), parent)
, _port(port, this)
, telnet_io(&_port)
, name(shell_name)
{
    //connect( this, &QShell::finished, this, &TelnetQShell::close );
    shell().cmd_name = name.c_str();
}


TelnetQShell::~TelnetQShell()
{
    terminate();
    close();
}

void TelnetQShell::close(){
    _port.close();
}



//-----------------------------------------------------------------------------
#include <string_utils.h>
QTelnetTCPServer::QTelnetTCPServer(QObject *parent)
: inherited(parent)
{}

volatile unsigned QTelnetTCPServer::id_counter = 0;

/**
* Processes incomming TCP connections
* @param socketDescriptor The descriptor of the conection
*/
void QTelnetTCPServer::incomingConnection(qintptr handle){
    //Accept the incomming client
    unsigned id = id_counter++;
    auto service = new_service( id, handle);
    connect( this, &QTelnetTCPServer::request_terminate_all
                    , service, &QShell::terminate
                    , Qt::DirectConnection );
    //service->take_own( std::move(*service) );
    service->start();
}

QTelnetTCPServer::service_t* QTelnetTCPServer::new_service( unsigned id, qintptr handle){
    return new service_t( handle, str_printf("telnet%u", id), nullptr );
}

