// ICS Whois client demo - C++Builder equivalent of OverbyteIcsWhoisCliTst1.pas
#include <vcl.h>
#pragma hdrstop

#include "OverbyteIcsWhoisCliTst1.h"
#pragma package(smart_init)
#pragma resource "*.dfm"

TWhoisDemoForm *WhoisDemoForm;

__fastcall TWhoisDemoForm::TWhoisDemoForm(TComponent *Owner) : TForm(Owner)
{
}

void __fastcall TWhoisDemoForm::CloseButtonClick(TObject *Sender)
{
    Close();
}

void __fastcall TWhoisDemoForm::FormCreate(TObject *Sender)
{
    Caption = Caption + IcsVerLitSample;
}

// Fills the server drop down from the "<suffix> <server>" entries in WhoisServers.
void __fastcall TWhoisDemoForm::FormShow(TObject *Sender)
{
    if (WhoisCli1->WhoisServers->Count > 0) {
        HostEdit->Items->Clear();
        for (int i = 0; i < WhoisCli1->WhoisServers->Count; i++) {
            String entry = WhoisCli1->WhoisServers->Strings[i];
            int space = entry.Pos(IcsSPACE);   // 1-based, 0 when absent
            if (space == 0)
                HostEdit->Items->Add(entry);
            else {
                String kind = entry.SubString(1, space);   // suffix including the trailing space
                if (kind == "00 ")
                    kind = "IP Addresses]";
                else if (kind == "?? ")
                    kind = "Top Level Domains]";
                else
                    kind = kind + "Domains]";
                HostEdit->Items->Add(entry.SubString(space + 1, entry.Length()) + " [" + kind);
            }
        }
        HostEdit->ItemIndex = 0;
    }

    // Post a message so startup work runs once the form is visible.
    PostMessage(Handle, WM_APPSTARTUP, 0, 0);
}

void __fastcall TWhoisDemoForm::WMAppStartup(TMessage &Msg)
{
    Update();   // let the window paint completely
    if (ParamCount() > 0) {
        QueryEdit->Text = ParamStr(1);
        QueryButtonClick(this);
    }
}

void __fastcall TWhoisDemoForm::QueryButtonClick(TObject *Sender)
{
    DisplayMemo->Clear();
    QueryButton->Enabled = false;
    CancelButton->Enabled = true;
    WhoisCli1->Query = QueryEdit->Text;
    WhoisCli1->Host = HostEdit->Text;
    if (WhoisMethod->ItemIndex == 0)
        WhoisCli1->StartAutoQuery();
    else
        WhoisCli1->StartQuery();
    DisplayMemo->Lines->Add("Query initiated for " + WhoisCli1->Query);
}

void __fastcall TWhoisDemoForm::WhoisCli1QueryDone(TObject *Sender, System::Word Error)
{
    DisplayMemo->Lines->Add(WhoisCli1->WhoisResp);
    DisplayMemo->Lines->Add("Query completed");
    QueryButton->Enabled = true;
    CancelButton->Enabled = false;
}

void __fastcall TWhoisDemoForm::CancelButtonClick(TObject *Sender)
{
    WhoisCli1->Abort();
    QueryButton->Enabled = true;
    CancelButton->Enabled = false;
}
