unit uCreateNotify;

interface

uses
  System.SysUtils, System.Types, System.UITypes, System.Classes,
  System.Variants, fOBS,  System.RegularExpressions,  Math,
  FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, fFontSettings,
  fColorSettings, FMX.StdCtrls, FMX.Edit, FMX.Controls.Presentation,
  FMX.ListBox, FMX.EditBox, FMX.SpinBox, FMX.Colors, uRecords;

type
  TfCreateNotify = class(TForm)
    btnESImageOpen: TButton;
    btnESSoundOpen: TButton;
    edtESImage: TEdit;
    edtESSound: TEdit;
    edtESTitle: TEdit;
    Label58: TLabel;
    Label68: TLabel;
    frColorSettings1: TfrColorSettings;
    frFontSettings2: TfrFontSettings;
    GroupBox10: TGroupBox;
    Label38: TLabel;
    sbTimeMsg: TSpinBox;
    Label39: TLabel;
    sbWebServerPort: TSpinBox;
    Label2: TLabel;
    cbEventsType: TComboBox;
    Label3: TLabel;
    edtIF: TEdit;
    btnCreateEvent: TButton;
    btnESTest: TButton;
    GroupBox1: TGroupBox;
    GroupBox2: TGroupBox;
    frFontSettings3: TfrFontSettings;
    edtESMessage: TEdit;
    procedure FormCreate(Sender: TObject);
    procedure btnCreateEventClick(Sender: TObject);
    procedure FormShow(Sender: TObject);
    procedure cbEventsTypeChange(Sender: TObject);
    procedure btnESTestClick(Sender: TObject);
  private
    { Private declarations }
    function GetColorFromColorPanel(aColor: TAlphaColor): string;
    function GetColorFromCCB(aColor: TAlphaColor): string;

    function GetColorFromRGBA(const s: string): TAlphaColor;
    function GetColorFromHex(const s: string): TAlphaColor;
  public
    { Public declarations }
    isEdit: boolean;
    oldPort: integer;
    procedure setRecord(aRec: TOBSNotify);
  end;

var
  fCreateNotify: TfCreateNotify;

implementation

uses uGeneral;

{$R *.fmx}

 function TfCreateNotify.GetColorFromRGBA(const s: string): TAlphaColor;
var
  Match: TMatch;
  r, g, b: Integer;
  a: Double;
  Rec: TAlphaColorRec;
begin
  Match := TRegEx.Match(s, 'rgba\((\d+),\s*(\d+),\s*(\d+),\s*([\d.]+)\)');
  if Match.Success then
  begin
    r := StrToInt(Match.Groups[1].Value);
    g := StrToInt(Match.Groups[2].Value);
    b := StrToInt(Match.Groups[3].Value);
    a := StrToFloat(Match.Groups[4].Value, TFormatSettings.Invariant);

    // Заполняем структуру вручную
    Rec.R := Byte(r);
    Rec.G := Byte(g);
    Rec.B := Byte(b);
    Rec.A := Round(a * 255);

    Result := Rec.Color;
  end
  else
    raise Exception.CreateFmt('Неверный формат rgba: %s', [s]);
end;

function TfCreateNotify.GetColorFromColorPanel(aColor: TAlphaColor): string;
var
  Color: TAlphaColor;
  r, G, B: Byte;
  A: Real;
  FS: TFormatSettings;
begin
  Color := aColor;
  r := TAlphaColorRec(Color).r;
  G := TAlphaColorRec(Color).G;
  B := TAlphaColorRec(Color).B;
  A := TAlphaColorRec(Color).A / 255; // Преобразуем альфа-канал в диапазон 0..1

  // Устанавливаем точку в качестве десятичного разделителя
  FS := TFormatSettings.Create;
  FS.DecimalSeparator := '.';

  result := Format('rgba(%d, %d, %d, %.2f)', [r, G, B, A], FS);
end;

function TfCreateNotify.GetColorFromCCB(aColor: TAlphaColor): string;
var
  Color: TAlphaColor;
  r, G, B: Byte;
begin
  Color := aColor;
  r := TAlphaColorRec(Color).r;
  G := TAlphaColorRec(Color).G;
  B := TAlphaColorRec(Color).B;
  result := Format('#%.2X%.2X%.2X', [r, G, B]);
end;

function TfCreateNotify.GetColorFromHex(const s: string): TAlphaColor;
var
  Hex: string;
  r, g, b: Integer;
  Rec: TAlphaColorRec;
begin
  // Убираем возможный символ #
  Hex := s.Trim;
  if Hex.StartsWith('#') then
    Hex := Hex.Substring(1);

  // Ожидаем ровно 6 символов (RRGGBB)
  if Length(Hex) <> 6 then
    raise Exception.CreateFmt('Неверный HEX цвет: %s', [s]);

  // Парсим компоненты
  r := StrToInt('$' + Copy(Hex, 1, 2));
  g := StrToInt('$' + Copy(Hex, 3, 2));
  b := StrToInt('$' + Copy(Hex, 5, 2));

  // Заполняем структуру
  Rec.R := Byte(r);
  Rec.G := Byte(g);
  Rec.B := Byte(b);
  Rec.A := 255; // полная непрозрачность

  Result := Rec.Color;
end;

procedure TfCreateNotify.setRecord(aRec: TOBSNotify);
var
  SavedColor: TAlphaColor;
begin
  with aRec do
  begin
    fCreateNotify.edtESImage.Text := Picture;
    fCreateNotify.edtESSound.Text := Sound;

    if TryStrToUInt('$' + ColorBlock, Cardinal(SavedColor)) then
      fCreateNotify.frColorSettings1.cpStyleBlockColor.Color := SavedColor
    else
      fCreateNotify.frColorSettings1.cpStyleBlockColor.Color :=
        TAlphaColorRec.Black;

    fCreateNotify.frColorSettings1.sbStyleBlockBorderSize.Value := SolidBorder;
    fCreateNotify.frColorSettings1.sbStyleBlockPadding.Value := Paddings;
    fCreateNotify.frColorSettings1.ccbStyleBorderColor.Color := GetColorFromHex(ColorBorder);
    fCreateNotify.frColorSettings1.ccbBColor.Color := GetColorFromHex(ColorBackground);
    fCreateNotify.frColorSettings1.cpStyleBlockColor.Color:=GetColorFromRGBA(ColorBlock);

    fCreateNotify.edtESTitle.Text := HeaderText;
    fCreateNotify.frFontSettings2.ccbFontColor.Color := GetColorFromHex(HeaderColorFont);
    fCreateNotify.frFontSettings2.sbFontSize.Value := HeaderSizeFont;
    fCreateNotify.frFontSettings2.cbFontStyleDefault.ItemIndex :=
     fCreateNotify.frFontSettings2.cbFontStyleDefault.Items.IndexOf(HeaderStyleFont);

    fCreateNotify.edtESMessage.Text := MessText;
    fCreateNotify.frFontSettings3.ccbFontColor.Color := GetColorFromHex(MessColorFont);
    fCreateNotify.frFontSettings3.sbFontSize.Value := MessSizeFont;
    fCreateNotify.frFontSettings3.cbFontStyleDefault.ItemIndex :=
    fCreateNotify.frFontSettings3.cbFontStyleDefault.Items.IndexOf(MessStyleFont);

    fCreateNotify.sbTimeMsg.Value := TimeMess;
    fCreateNotify.cbEventsType.ItemIndex := TypeEvent;
    fCreateNotify.edtIF.Text := TypeEdit;
    fCreateNotify.sbWebServerPort.Value := port;
    oldPort:=port;
  end;
end;

procedure TfCreateNotify.btnCreateEventClick(Sender: TObject);
var
  OBSNotify: TOBSNotify;
begin
  with OBSNotify do
  begin
    Picture := edtESImage.Text;
    Sound := edtESSound.Text;

    ColorBlock := GetColorFromColorPanel
      (frColorSettings1.cpStyleBlockColor.Color);
    SolidBorder := round(frColorSettings1.sbStyleBlockBorderSize.Value);
    Paddings := round(frColorSettings1.sbStyleBlockPadding.Value);
    ColorBorder := GetColorFromCCB(frColorSettings1.ccbStyleBorderColor.Color);
    ColorBackground := GetColorFromCCB(frColorSettings1.ccbBColor.Color);

    HeaderText := edtESTitle.Text;
    HeaderColorFont := GetColorFromCCB(frFontSettings2.ccbFontColor.Color);
    HeaderSizeFont := round(frFontSettings2.sbFontSize.Value);
    HeaderStyleFont := frFontSettings2.cbFontStyleDefault.Text;

    MessText := edtESMessage.Text;
    MessColorFont := GetColorFromCCB(frFontSettings3.ccbFontColor.color);
    MessSizeFont := round(frFontSettings3.sbFontSize.Value);
    MessStyleFont := frFontSettings3.cbFontStyleDefault.Text;

    TimeMess := round(sbTimeMsg.Value);
    TypeEvent := cbEventsType.ItemIndex;
    TypeEdit := edtIF.Text;
    port := round(sbWebServerPort.Value);
  end;
  if isEdit then
    TTW_Bot.frOBS1.EdtNotify(OBSNotify, oldPort)
  else
    TTW_Bot.frOBS1.AddNotify(OBSNotify);
  close;
end;





procedure TfCreateNotify.btnESTestClick(Sender: TObject);
var
  se: TStyleEvent;
  i: Integer;
 ws:TEventWebServers;
begin

  se.Title := edtESTitle.Text;
  se.Context := edtESMessage.Text;
  se.Url := edtESImage.Text;
  se.SoundURL := edtESSound.Text;
  se.Timestamp := Now;
  se.TimeMsg := round(sbTimeMsg.Value);
  se.BorderColor := GetColorFromCCB(frColorSettings1.ccbStyleBorderColor.Color);
  se.BorderSize := round(frColorSettings1.sbStyleBlockBorderSize.Value);
  se.BlockColor := GetColorFromColorPanel(frColorSettings1.cpStyleBlockColor.Color);
  se.FontTitle.Font := frFontSettings2.cbFontStyleDefault.Text;
  se.FontTitle.Size := round(frFontSettings2.sbFontSize.Value);
  se.FontTitle.Color := GetColorFromCCB(frFontSettings2.ccbFontColor.Color);
  se.FontContext.Font := frFontSettings3.cbFontStyleDefault.Text;
  se.FontContext.Size := round(frFontSettings3.sbFontSize.Value);
  se.FontContext.Color := GetColorFromCCB(frFontSettings3.ccbFontColor.Color);
  se.RequireInteraction := True;
  for i := 0 to TTW_Bot.frOBS1.EventWebServers.Count - 1 do
  begin
    if TTW_Bot.frOBS1.EventWebServers[i].port = oldPort then
    ws:=TTW_Bot.frOBS1.EventWebServers[i];


  end;
  ws.WebServerChat.addMessage(se);
end;

procedure TfCreateNotify.cbEventsTypeChange(Sender: TObject);
begin
   Label3.Visible := cbEventsType.ItemIndex = 4;
  edtIF.Visible := cbEventsType.ItemIndex = 4;
end;

procedure TfCreateNotify.FormCreate(Sender: TObject);
var
  i: integer;
  SavedColor: TAlphaColor;
  c: TComponent;
  ColorStr: string;
begin
  isEdit := false;
  for i := 0 to frColorSettings1.ComponentCount - 1 do
  begin
    c := frColorSettings1.Components[i];
    if c is TComboBox then
    begin
      TComboBox(c).ItemIndex :=
        strtoint(DB.ReadSetting(TComboBox(c).Name, '0'));
    end;
    if c is TColorComboBox then
    begin
      TColorComboBox(c).ItemIndex :=
        strtoint(DB.ReadSetting(TComboBox(c).Name, '147'));
    end;
    if c is TSpinBox then
    begin
      TSpinBox(c).Text := DB.ReadSetting(TSpinBox(c).Name, '1');
    end;
    if c is TColorPanel then
    begin
      ColorStr := DB.ReadSetting(TColorPanel(c).Name, 'FF000000');
      if TryStrToUInt('$' + ColorStr, Cardinal(SavedColor)) then
        TColorPanel(c).Color := SavedColor
      else
        TColorPanel(c).Color := TAlphaColorRec.Black;
    end;
    if c is TEdit then
    begin
      if TEdit(c).Name <> 'edtPortServer' then
        TEdit(c).Text := DB.ReadSetting(TEdit(c).Name, '0');
    end;
    if c is TCheckBox then
    begin
      TCheckBox(c).IsChecked := DB.ReadSetting(TCheckBox(c).Name) = '1';
    end;
  end;
  for i := 0 to frFontSettings2.ComponentCount - 1 do
  begin
    c := frFontSettings2.Components[i];
    if c is TComboBox then
    begin
      TComboBox(c).ItemIndex :=
        strtoint(DB.ReadSetting(TComboBox(c).Name, '0'));
    end;
    if c is TColorComboBox then
    begin
      TColorComboBox(c).ItemIndex :=
        strtoint(DB.ReadSetting(TComboBox(c).Name, '147'));
    end;
    if c is TSpinBox then
    begin
      TSpinBox(c).Text := DB.ReadSetting(TSpinBox(c).Name, '1');
    end;
    if c is TColorPanel then
    begin
      ColorStr := DB.ReadSetting(TColorPanel(c).Name, 'FF000000');
      if TryStrToUInt('$' + ColorStr, Cardinal(SavedColor)) then
        TColorPanel(c).Color := SavedColor
      else
        TColorPanel(c).Color := TAlphaColorRec.Black;
    end;
    if c is TEdit then
    begin
      if TEdit(c).Name <> 'edtPortServer' then
        TEdit(c).Text := DB.ReadSetting(TEdit(c).Name, '0');
    end;
    if c is TCheckBox then
    begin
      TCheckBox(c).IsChecked := DB.ReadSetting(TCheckBox(c).Name) = '1';
    end;
  end;

  for i := 0 to frFontSettings3.ComponentCount - 1 do
  begin
    c := frFontSettings3.Components[i];
    if c is TComboBox then
    begin
      TComboBox(c).ItemIndex :=
        strtoint(DB.ReadSetting(TComboBox(c).Name, '0'));
    end;
    if c is TColorComboBox then
    begin
      TColorComboBox(c).ItemIndex :=
        strtoint(DB.ReadSetting(TComboBox(c).Name, '147'));
    end;
    if c is TSpinBox then
    begin
      TSpinBox(c).Text := DB.ReadSetting(TSpinBox(c).Name, '1');
    end;
    if c is TColorPanel then
    begin
      ColorStr := DB.ReadSetting(TColorPanel(c).Name, 'FF000000');
      if TryStrToUInt('$' + ColorStr, Cardinal(SavedColor)) then
        TColorPanel(c).Color := SavedColor
      else
        TColorPanel(c).Color := TAlphaColorRec.Black;
    end;
    if c is TEdit then
    begin
      if TEdit(c).Name <> 'edtPortServer' then
        TEdit(c).Text := DB.ReadSetting(TEdit(c).Name, '0');
    end;
    if c is TCheckBox then
    begin
      TCheckBox(c).IsChecked := DB.ReadSetting(TCheckBox(c).Name) = '1';
    end;
  end;

  var
  cDir := myconst.fontsPath; // Искать в папке с программой
  var
  FileName := '*.*'; // Ищем все файлы
  ChDir(cDir); // войти в каталог
  var
    SearchRec: TSearchRec;
  if FindFirst(FileName, faArchive, SearchRec) = 0 then
    repeat
      if (SearchRec.Attr and faAnyFile) = SearchRec.Attr then
      begin
        frFontSettings2.cbFontStyleDefault.Items.Add(SearchRec.Name);
        frFontSettings3.cbFontStyleDefault.Items.Add(SearchRec.Name);


      end;
    until FindNext(SearchRec) <> 0;
  ChDir('..');

end;

procedure TfCreateNotify.FormShow(Sender: TObject);
begin
  if isEdit then
  begin
    btnCreateEvent.Text := 'Изменить оповещение';
  end
  else
  begin
    btnCreateEvent.Text := 'Создать оповещение';
  end;
end;

end.
