/*
  ICS ServiceTcp demo - C++Builder translation of the Delphi demo OverbyteIcsServiceTcp1.pas
  (demos-delphi-vcl), ICS V9.8.

  Runs the TTcpDaemon telnet-style server (OverbyteIcsServiceCmd) inside a Windows service,
  "ICS Tcp Service". Install it from a command window with administrator rights:
      OverbyteIcsServiceTcp /install        (and /uninstall to remove it)
  then start it from Computer Management or "net start". A service has no window, so everything
  is written to a daily log file, ServiceTcp-yyyymmdd.log. Once running, connect a telnet client to
  port 2120 and type help.

  How this C++ version differs from the Delphi original, apart from syntax:
  - The Delphi header says to connect to port 2010; the daemon listens on 2120.
  - ServiceStart now reports the service as not started when the daemon fails to start; the Delphi
    handler only logged the exception, and the service stayed in the running state.
  - The unused ServiceTcpVersion and CopyRight constants are not converted.
*/

#include <vcl.h>
#pragma hdrstop

#include "OverbyteIcsServiceTcp1.h"

#pragma package(smart_init)
#pragma resource "*.dfm"

TIcsTcpServce *IcsTcpServce;

namespace {

const String SimpLogName = "\"ServiceTcp-\"yyyymmdd\".log\"";   // daily log file name mask

} // namespace

__fastcall TIcsTcpServce::TIcsTcpServce(TComponent *Owner)
    : TService(Owner)
{
}

// Entry point the service manager calls for control requests (stop, pause, ...).
void __stdcall ServiceController(DWORD CtrlCode)
{
    IcsTcpServce->Controller(CtrlCode);
}

TServiceController __fastcall TIcsTcpServce::GetServiceController(void)
{
    return static_cast<TServiceController>(ServiceController);
}

void __fastcall TIcsTcpServce::ServiceStart(TService *Sender, bool &Started)
{
    Display("Creating and Starting Daemon");
    try {
        FTcpDaemon.reset(new TTcpDaemon);
        FTcpDaemon->SetBanner(DisplayName + " Ready");
        FTcpDaemon->OnDisplay = Display;
        FTcpDaemon->Start();
        Started = true;
    }
    catch (Exception &E) {
        Display("Exception Starting Service: " + E.Message);
        Started = false;   // the Delphi leaves Started at its default of true
    }
}

void __fastcall TIcsTcpServce::ServiceStop(TService *Sender, bool &Stopped)
{
    Display("Stopping Service");
    FTcpDaemon->Stop();
    Stopped = true;
}

void __fastcall TIcsTcpServce::ServiceExecute(TService *Sender)
{
    Display("Starting Message Loop");
    while (!Terminated)
        ServiceThread->ProcessRequests(true);
}

void __fastcall TIcsTcpServce::Display(const String &Msg)
{
    // A service has no access to the GUI, so every message goes to the daily log file.
    IcsSimpleLogging(SimpLogName, Msg);
}

void __fastcall TIcsTcpServce::ServiceCreate(TObject *Sender)
{
    Display("Created Service");
}

void __fastcall TIcsTcpServce::ServiceDestroy(TObject *Sender)
{
    FTcpDaemon.reset();
}
