//---------------------------------------------------------------------------

#include <vcl.h>
#include <Shellapi.h>
#include <System.NetEncoding.hpp>
#pragma hdrstop

#include "uMain.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "MySQLUniProvider"
#pragma link "UniProvider"
#pragma resource "*.dfm"
TfMain *fMain;
//---------------------------------------------------------------------------
__fastcall TfMain::TfMain(TComponent* Owner)
  : TForm(Owner)
{
}
//---------------------------------------------------------------------------

void __fastcall TfMain::FormCreate(TObject *Sender)
{
  Randomize();
  LogLine("App started");
}
//---------------------------------------------------------------------------

void __fastcall TfMain::btnOpenTaskItemsClick(TObject *Sender)
{
  const UnicodeString userId = edtUserId->Text.Trim();
  const UnicodeString taskId = edtTaskId->Text.Trim();
  const UnicodeString baseUrl = edtWebUrl->Text.Trim();
  const int expSeconds = StrToIntDef(edtExpSeconds->Text.Trim(), 60);

  if (userId.IsEmpty() || taskId.IsEmpty() || baseUrl.IsEmpty())
  {
    LogLine("Missing required input (userId, taskId, or webUrl)");
    return;
  }

  const int codeInt = 100000 + Random(900000);
  const UnicodeString urlCode = IntToStr(codeInt);

  LogLine("Generated URL_CODE=" + urlCode);

  try
  {
    if (!ucETask->Connected)
    {
      LogLine("Connecting to MariaDB...");
      ucETask->Connect();
      LogLine("Connected");
    }

    LogLine("Inserting row into web_tasks_url...");

    uqWebTasksUrl->Close();
    uqWebTasksUrl->SQL->Text =
      "insert into web_tasks_url (USER_ID, TASK_ID, URL_CODE, URL_TIME, URL_TIME_EXP) "
      "values (:USER_ID, :TASK_ID, :URL_CODE, NOW(), :URL_TIME_EXP)";

    uqWebTasksUrl->ParamByName("USER_ID")->AsString = userId;
    uqWebTasksUrl->ParamByName("TASK_ID")->AsString = taskId;
    uqWebTasksUrl->ParamByName("URL_CODE")->AsString = urlCode;
    uqWebTasksUrl->ParamByName("URL_TIME_EXP")->AsInteger = expSeconds;

    uqWebTasksUrl->ExecSQL();

    LogLine("Insert OK");
  }
  catch (const Exception &e)
  {
    LogLine("DB ERROR: " + e.Message);
    return;
  }

  const UnicodeString launchUrl = BuildLaunchUrl(baseUrl, userId, taskId, urlCode);
  if (launchUrl.IsEmpty())
  {
    LogLine("Launch URL build failed");
    return;
  }

  LogLine("Launching browser:");
  LogLine(launchUrl);

  ShellExecute(0, L"open", launchUrl.w_str(), 0, 0, SW_SHOWNORMAL);
}
//---------------------------------------------------------------------------

void TfMain::LogLine(const String &message)
{
  const String stamp = FormatDateTime("yyyy-mm-dd hh:nn:ss.zzz", Now());
  memoLog->Lines->Add(stamp + "  " + message);
  memoLog->SelStart = memoLog->Text.Length();
}

//---------------------------------------------------------------------------

String TfMain::BuildLaunchUrl(const String &baseUrl, const String &userId, const String &taskId, const String &code)
{
  String cleanBaseUrl = baseUrl.Trim();
  if (cleanBaseUrl.IsEmpty())
    return "";

  String sep = cleanBaseUrl.Pos("?") > 0 ? "&" : "?";

  String qUserId = TNetEncoding::URL->Encode(userId);
  String qTaskId = TNetEncoding::URL->Encode(taskId);
  String qCode = TNetEncoding::URL->Encode(code);

  return cleanBaseUrl + sep + "user_id=" + qUserId + "&task_id=" + qTaskId + "&url_code=" + qCode;
}


