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

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

#include "fMain.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "MySQLUniProvider"
#pragma link "UniProvider"
#pragma resource "*.dfm"
TfrmMain *frmMain;
//---------------------------------------------------------------------------
__fastcall TfrmMain::TfrmMain(TComponent* Owner)
  : TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TfrmMain::FormCreate(TObject *Sender)
{
  Randomize();
  LogLine( "ucETask->Server: " + ucETask->Server );
  LogLine( "ucETask->Database: " + ucETask->Database );
  LogLine( "ucETask->Username: " + ucETask->Username );
  LogLine( "ucETask->Password: " + ucETask->Password );
  LogLine( "App started" );
}
//---------------------------------------------------------------------------
void __fastcall TfrmMain::btnOpenTaskItemsClick(TObject *Sender)
{
  String userId = edtUserId->Text.Trim();
  String taskId = edtTaskId->Text.Trim();
  String baseUrl = edtWebUrl->Text.Trim();
  int expSeconds = StrToIntDef(edtExpSeconds->Text.Trim(), 5);

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

  int codeInt = 100000 + Random(900000);
  String 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;
  }

  String 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 TfrmMain::LogLine(String message)
{
  String stamp = FormatDateTime("yyyy-mm-dd hh:nn:ss.zzz", Now());
  memoLog->Lines->Add(stamp + "  " + message);
  memoLog->SelStart = memoLog->Text.Length();
}
//---------------------------------------------------------------------------
String TfrmMain::BuildLaunchUrl(String baseUrl, String userId, String taskId, String code)
{
  String cleanBaseUrl = baseUrl.Trim();
  if( cleanBaseUrl.IsEmpty() )
    return "";

  return cleanBaseUrl + "?user_id=" + userId + "&task_id=" + taskId + "&url_code=" + code;
}
//---------------------------------------------------------------------------
void __fastcall TfrmMain::btnTaskItemsLoginClick(TObject *Sender)
{
  String userId = edtUserId->Text.Trim();
  String taskId = edtTaskId->Text.Trim();
  String baseUrl = edtWebUrl->Text.Trim();

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

  String urlCode = 'WebLogin';

  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 = 0;

    uqWebTasksUrl->ExecSQL();

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

  String launchUrl = baseUrl + "?user_id=" + userId + "&task_id=" + taskId;

  if( launchUrl.IsEmpty() ){
    LogLine("Launch URL build failed");
    return;
  }

  LogLine( "Task Items Login url:" + launchUrl );

  //ShellExecute( 0, L"open", launchUrl.w_str(), 0, 0, SW_SHOWNORMAL );
}
//---------------------------------------------------------------------------
void __fastcall TfrmMain::btnConnectClick(TObject *Sender)
{
  ucETask->Connect();
  LogLine( "Connected to database" );
}
//---------------------------------------------------------------------------

