﻿unit frm_ConfigBascula;

{ Configuración de la comunicación con la báscula, reglas de control de peso y conexión a BD.
  Formulario construido íntegramente por código (sin DFM).
  Acceso protegido por contraseña (CONFIG_PASSWORD). }

interface

uses
  Winapi.Windows, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls,
  Vcl.Forms, Vcl.StdCtrls, Vcl.ExtCtrls, uPesadoConfig;

type
  TfrmConfigBascula = class(TForm)
  private
    FConfig: TPesadoConfig;
    cbPuerto, cbBaud, cbDataBits, cbParidad, cbStopBits, cbUnidadTrama, cbUnidadArticulo: TComboBox;
    edtComando, edtIntervalo, edtTolerancia, edtTara, edtPesoMin, edtUmbralCero,
    edtMuestras, edtTolEstable: TEdit;
    edtDBServer, edtDBPort, edtDBDatabase, edtDBUser, edtDBPassword: TEdit;
    chkSimulado, chkSonido: TCheckBox;
    memPrueba: TMemo;
    function AddCombo(AParent: TWinControl; const ACaption: string; ATop: Integer; const AItems: array of string): TComboBox;
    function AddEdit(AParent: TWinControl; const ACaption: string; ATop: Integer): TEdit;
    procedure CargarEnPantalla;
    function LeerDePantalla(out AConfig: TPesadoConfig): Boolean;
    procedure btnProbarClick(Sender: TObject);
    procedure btnProbarBDClick(Sender: TObject);
    procedure btnGuardarClick(Sender: TObject);
  public
    constructor Create(AOwner: TComponent); override;
    class function Ejecutar(var AConfig: TPesadoConfig): Boolean;
  end;

function PedirPasswordAdmin(AOwner: TComponent): Boolean;

implementation

uses
  System.Math, System.UITypes, Vcl.Dialogs, uBasculaSerial, uPesadoDB;

function FloatToStrInv(AValue: Double): string;
begin
  Result := FloatToStr(AValue);
end;

function PedirPasswordAdmin(AOwner: TComponent): Boolean;
var
  LForm: TForm;
  LLbl: TLabel;
  LEdit: TEdit;
  LOk, LCancel: TButton;
begin
  LForm := TForm.CreateNew(AOwner);
  try
    LForm.Caption := 'Acceso restringido';
    LForm.BorderStyle := bsDialog;
    LForm.Position := poScreenCenter;
    LForm.ClientWidth := 460;
    LForm.ClientHeight := 210;
    LForm.Font.Name := 'Segoe UI';
    LForm.Font.Size := 14;

    LLbl := TLabel.Create(LForm);
    LLbl.Parent := LForm;
    LLbl.SetBounds(24, 18, 400, 30);
    LLbl.Caption := 'Introduzca la contraseña de administrador:';

    LEdit := TEdit.Create(LForm);
    LEdit.Parent := LForm;
    LEdit.SetBounds(24, 60, 410, 40);
    LEdit.PasswordChar := '*';
    LEdit.Font.Size := 18;

    LOk := TButton.Create(LForm);
    LOk.Parent := LForm;
    LOk.SetBounds(24, 130, 195, 56);
    LOk.Caption := 'ACEPTAR';
    LOk.Default := True;
    LOk.ModalResult := mrOk;

    LCancel := TButton.Create(LForm);
    LCancel.Parent := LForm;
    LCancel.SetBounds(239, 130, 195, 56);
    LCancel.Caption := 'CANCELAR';
    LCancel.Cancel := True;
    LCancel.ModalResult := mrCancel;

    LForm.ActiveControl := LEdit;
    Result := (LForm.ShowModal = mrOk) and (LEdit.Text = CONFIG_PASSWORD);
    if (LForm.ModalResult = mrOk) and not Result then
      MessageDlg('Contraseña incorrecta.', mtError, [mbOK], 0);
  finally
    LForm.Free;
  end;
end;

{ TfrmConfigBascula }

constructor TfrmConfigBascula.Create(AOwner: TComponent);
const
  COL2 = 470;
var
  LGrpCom, LGrpCtrl, LGrpDB, LGrpTest: TGroupBox;
  LBtn: TButton;
  LPanelBtn: TPanel;
  LLblInfo: TLabel;
  LTop: Integer;
begin
  inherited CreateNew(AOwner);
  Caption := 'Configuración de báscula, control de peso y base de datos';
  BorderStyle := bsDialog;
  Position := poScreenCenter;
  ClientWidth := 940;
  ClientHeight := 780;
  Font.Name := 'Segoe UI';
  Font.Size := 11;

  // --- Comunicación ---
  LGrpCom := TGroupBox.Create(Self);
  LGrpCom.Parent := Self;
  LGrpCom.SetBounds(12, 10, 450, 400);
  LGrpCom.Caption := ' Comunicación con la báscula (Puerto COM) ';

  cbPuerto := AddCombo(LGrpCom, 'Puerto COM', 28, []);
  ListarPuertosCOM(cbPuerto.Items);
  cbPuerto.Style := csDropDown;
  cbBaud := AddCombo(LGrpCom, 'Velocidad (baudios)', 66, ['1200', '2400', '4800', '9600', '19200', '38400', '57600', '115200']);
  cbDataBits := AddCombo(LGrpCom, 'Bits de datos', 104, ['7', '8']);
  cbParidad := AddCombo(LGrpCom, 'Paridad', 142, ['Ninguna', 'Impar', 'Par']);
  cbStopBits := AddCombo(LGrpCom, 'Bits de parada', 180, ['1', '1.5', '2']);
  edtComando := AddEdit(LGrpCom, 'Comando petición (HEX)', 218);
  edtComando.Hint := 'Vacío si la báscula transmite en continuo. Ej.: 05 (ENQ), 24 ($), 50 0D 0A';
  edtComando.ShowHint := True;
  edtIntervalo := AddEdit(LGrpCom, 'Intervalo lectura (ms)', 256);
  cbUnidadTrama := AddCombo(LGrpCom, 'Unidad por defecto trama', 294, ['Kilogramos', 'Gramos']);

  chkSimulado := TCheckBox.Create(Self);
  chkSimulado.Parent := LGrpCom;
  chkSimulado.SetBounds(16, 342, 420, 28);
  chkSimulado.Caption := 'MODO SIMULACIÓN (pruebas sin báscula)';

  // --- Control ---
  LGrpCtrl := TGroupBox.Create(Self);
  LGrpCtrl.Parent := Self;
  LGrpCtrl.SetBounds(COL2, 10, 458, 350);
  LGrpCtrl.Caption := ' Reglas de control de peso ';

  cbUnidadArticulo := AddCombo(LGrpCtrl, 'Unidad de ge_articulos.peso', 28, ['Kilogramos', 'Gramos']);
  edtTolerancia := AddEdit(LGrpCtrl, 'Tolerancia déficit (%)', 66);
  edtTara := AddEdit(LGrpCtrl, 'Tara envase a descontar (g)', 104);
  edtPesoMin := AddEdit(LGrpCtrl, 'Peso mínimo detección (g)', 142);
  edtUmbralCero := AddEdit(LGrpCtrl, 'Umbral plato vacío (g)', 180);
  edtMuestras := AddEdit(LGrpCtrl, 'Lecturas para estabilidad', 218);
  edtTolEstable := AddEdit(LGrpCtrl, 'Variación estable máx. (g)', 256);

  chkSonido := TCheckBox.Create(Self);
  chkSonido.Parent := LGrpCtrl;
  chkSonido.SetBounds(16, 300, 420, 28);
  chkSonido.Caption := 'Avisos sonoros (OK y alarma de rechazo)';

  // --- Base de Datos ---
  LGrpDB := TGroupBox.Create(Self);
  LGrpDB.Parent := Self;
  LGrpDB.SetBounds(12, 418, 450, 280);
  LGrpDB.Caption := ' Conexión a Base de Datos (MariaDB / MySQL) ';

  edtDBServer := AddEdit(LGrpDB, 'Servidor (Host / IP)', 28);
  edtDBPort := AddEdit(LGrpDB, 'Puerto TCP', 66);
  edtDBDatabase := AddEdit(LGrpDB, 'Base de datos', 104);
  edtDBUser := AddEdit(LGrpDB, 'Usuario', 142);
  edtDBPassword := AddEdit(LGrpDB, 'Contraseña', 180);
  edtDBPassword.PasswordChar := '*';

  LBtn := TButton.Create(Self);
  LBtn.Parent := LGrpDB;
  LBtn.SetBounds(240, 222, 200, 44);
  LBtn.Caption := 'Probar conexión BD';
  LBtn.OnClick := btnProbarBDClick;

  // --- Prueba ---
  LGrpTest := TGroupBox.Create(Self);
  LGrpTest.Parent := Self;
  LGrpTest.SetBounds(COL2, 368, 458, 330);
  LGrpTest.Caption := ' Diagnóstico y pruebas (Báscula COM / Base de Datos) ';

  memPrueba := TMemo.Create(Self);
  memPrueba.Parent := LGrpTest;
  memPrueba.SetBounds(12, 28, 434, 232);
  memPrueba.ReadOnly := True;
  memPrueba.ScrollBars := ssVertical;
  memPrueba.Font.Name := 'Consolas';
  memPrueba.Font.Size := 10;

  LBtn := TButton.Create(Self);
  LBtn.Parent := LGrpTest;
  LBtn.SetBounds(12, 268, 220, 48);
  LBtn.Caption := 'Probar puerto COM (3 s)';
  LBtn.OnClick := btnProbarClick;

  // --- Botonera ---
  LPanelBtn := TPanel.Create(Self);
  LPanelBtn.Parent := Self;
  LPanelBtn.Align := alBottom;
  LPanelBtn.Height := 70;
  LPanelBtn.BevelOuter := bvNone;

  LLblInfo := TLabel.Create(Self);
  LLblInfo.Parent := LPanelBtn;
  LLblInfo.SetBounds(14, 24, 500, 24);
  LLblInfo.Font.Size := 10;
  LLblInfo.Font.Color := clGrayText;
  LLblInfo.Caption := 'Archivo cifrado: ' + ExtractFileName(RutaCfgPesado);

  LTop := 8;
  LBtn := TButton.Create(Self);
  LBtn.Parent := LPanelBtn;
  LBtn.SetBounds(ClientWidth - 400, LTop, 185, 54);
  LBtn.Caption := 'GUARDAR';
  LBtn.Default := True;
  LBtn.OnClick := btnGuardarClick;

  LBtn := TButton.Create(Self);
  LBtn.Parent := LPanelBtn;
  LBtn.SetBounds(ClientWidth - 200, LTop, 185, 54);
  LBtn.Caption := 'CANCELAR';
  LBtn.Cancel := True;
  LBtn.ModalResult := mrCancel;
end;

function TfrmConfigBascula.AddCombo(AParent: TWinControl; const ACaption: string; ATop: Integer;
  const AItems: array of string): TComboBox;
var
  LLbl: TLabel;
  I: Integer;
begin
  LLbl := TLabel.Create(Self);
  LLbl.Parent := AParent;
  LLbl.SetBounds(16, ATop + 4, 220, 24);
  LLbl.Caption := ACaption;
  Result := TComboBox.Create(Self);
  Result.Parent := AParent;
  Result.SetBounds(240, ATop, 200, 28);
  Result.Style := csDropDownList;
  for I := Low(AItems) to High(AItems) do
    Result.Items.Add(AItems[I]);
end;

function TfrmConfigBascula.AddEdit(AParent: TWinControl; const ACaption: string; ATop: Integer): TEdit;
var
  LLbl: TLabel;
begin
  LLbl := TLabel.Create(Self);
  LLbl.Parent := AParent;
  LLbl.SetBounds(16, ATop + 4, 220, 24);
  LLbl.Caption := ACaption;
  Result := TEdit.Create(Self);
  Result.Parent := AParent;
  Result.SetBounds(240, ATop, 200, 28);
end;

procedure TfrmConfigBascula.CargarEnPantalla;
begin
  edtDBServer.Text := FConfig.DBServer;
  edtDBPort.Text := IntToStr(FConfig.DBPort);
  edtDBDatabase.Text := FConfig.DBDatabase;
  edtDBUser.Text := FConfig.DBUser;
  edtDBPassword.Text := FConfig.DBPassword;

  cbPuerto.Text := FConfig.Puerto;
  cbBaud.ItemIndex := cbBaud.Items.IndexOf(IntToStr(FConfig.BaudRate));
  if cbBaud.ItemIndex < 0 then
    cbBaud.ItemIndex := cbBaud.Items.IndexOf('9600');
  cbDataBits.ItemIndex := cbDataBits.Items.IndexOf(IntToStr(FConfig.DataBits));
  if cbDataBits.ItemIndex < 0 then
    cbDataBits.ItemIndex := 1;
  cbParidad.ItemIndex := EnsureRange(FConfig.Paridad, 0, 2);
  cbStopBits.ItemIndex := EnsureRange(FConfig.StopBits, 0, 2);
  edtComando.Text := FConfig.ComandoPeticionHex;
  edtIntervalo.Text := IntToStr(FConfig.IntervaloMs);
  cbUnidadTrama.ItemIndex := Ord(FConfig.UnidadTrama);
  chkSimulado.Checked := FConfig.Simulado;

  cbUnidadArticulo.ItemIndex := Ord(FConfig.UnidadArticulo);
  edtTolerancia.Text := FloatToStrInv(FConfig.ToleranciaPorc);
  edtTara.Text := FloatToStrInv(FConfig.TaraEnvaseGr);
  edtPesoMin.Text := FloatToStrInv(FConfig.PesoMinimoGr);
  edtUmbralCero.Text := FloatToStrInv(FConfig.UmbralCeroGr);
  edtMuestras.Text := IntToStr(FConfig.MuestrasEstables);
  edtTolEstable.Text := FloatToStrInv(FConfig.ToleranciaEstableGr);
  chkSonido.Checked := FConfig.SonidoActivo;
end;

function TfrmConfigBascula.LeerDePantalla(out AConfig: TPesadoConfig): Boolean;

  function LeerFloat(AEdit: TEdit; const ANombre: string; out AValor: Double): Boolean;
  begin
    Result := TryStrToFloat(StringReplace(Trim(AEdit.Text), '.', FormatSettings.DecimalSeparator, []), AValor)
      and (AValor >= 0);
    if not Result then
    begin
      MessageDlg('Valor no válido en "' + ANombre + '".', mtWarning, [mbOK], 0);
      AEdit.SetFocus;
    end;
  end;

  function LeerInt(AEdit: TEdit; const ANombre: string; out AValor: Integer): Boolean;
  begin
    Result := TryStrToInt(Trim(AEdit.Text), AValor) and (AValor > 0);
    if not Result then
    begin
      MessageDlg('Valor no válido en "' + ANombre + '".', mtWarning, [mbOK], 0);
      AEdit.SetFocus;
    end;
  end;

begin
  Result := False;
  AConfig := FConfig;

  AConfig.DBServer := Trim(edtDBServer.Text);
  if AConfig.DBServer = '' then
  begin
    MessageDlg('Indique el servidor de base de datos.', mtWarning, [mbOK], 0);
    edtDBServer.SetFocus;
    Exit;
  end;
  if not LeerInt(edtDBPort, 'Puerto TCP de base de datos', AConfig.DBPort) then Exit;
  AConfig.DBDatabase := Trim(edtDBDatabase.Text);
  if AConfig.DBDatabase = '' then
  begin
    MessageDlg('Indique el nombre de la base de datos.', mtWarning, [mbOK], 0);
    edtDBDatabase.SetFocus;
    Exit;
  end;
  AConfig.DBUser := Trim(edtDBUser.Text);
  if AConfig.DBUser = '' then
  begin
    MessageDlg('Indique el usuario de la base de datos.', mtWarning, [mbOK], 0);
    edtDBUser.SetFocus;
    Exit;
  end;
  AConfig.DBPassword := edtDBPassword.Text;

  AConfig.Puerto := UpperCase(Trim(cbPuerto.Text));
  if AConfig.Puerto = '' then
  begin
    MessageDlg('Indique el puerto COM.', mtWarning, [mbOK], 0);
    Exit;
  end;
  AConfig.BaudRate := StrToIntDef(cbBaud.Text, 9600);
  AConfig.DataBits := StrToIntDef(cbDataBits.Text, 8);
  AConfig.Paridad := Max(0, cbParidad.ItemIndex);
  AConfig.StopBits := Max(0, cbStopBits.ItemIndex);
  AConfig.ComandoPeticionHex := Trim(edtComando.Text);
  AConfig.UnidadTrama := TUnidadPeso(Max(0, cbUnidadTrama.ItemIndex));
  AConfig.Simulado := chkSimulado.Checked;
  AConfig.UnidadArticulo := TUnidadPeso(Max(0, cbUnidadArticulo.ItemIndex));
  AConfig.SonidoActivo := chkSonido.Checked;

  if not LeerInt(edtIntervalo, 'Intervalo lectura', AConfig.IntervaloMs) then Exit;
  if not LeerFloat(edtTolerancia, 'Tolerancia déficit', AConfig.ToleranciaPorc) then Exit;
  if not LeerFloat(edtTara, 'Tara envase', AConfig.TaraEnvaseGr) then Exit;
  if not LeerFloat(edtPesoMin, 'Peso mínimo detección', AConfig.PesoMinimoGr) then Exit;
  if not LeerFloat(edtUmbralCero, 'Umbral plato vacío', AConfig.UmbralCeroGr) then Exit;
  if not LeerInt(edtMuestras, 'Lecturas para estabilidad', AConfig.MuestrasEstables) then Exit;
  if not LeerFloat(edtTolEstable, 'Variación estable máx.', AConfig.ToleranciaEstableGr) then Exit;

  if AConfig.UmbralCeroGr >= AConfig.PesoMinimoGr then
  begin
    MessageDlg('El umbral de plato vacío debe ser menor que el peso mínimo de detección.', mtWarning, [mbOK], 0);
    Exit;
  end;
  if AConfig.MuestrasEstables < 2 then
    AConfig.MuestrasEstables := 2;
  Result := True;
end;

procedure TfrmConfigBascula.btnProbarBDClick(Sender: TObject);
var
  LCfg: TPesadoConfig;
  LMensaje: string;
  LOk: Boolean;
begin
  if not LeerDePantalla(LCfg) then
    Exit;
  memPrueba.Lines.Text := Format('Conectando a %s:%d (%s)...', [LCfg.DBServer, LCfg.DBPort, LCfg.DBDatabase]);
  Screen.Cursor := crHourGlass;
  try
    Application.ProcessMessages;
    LOk := TPesadoDB.ProbarConexion(LCfg, LMensaje);
  finally
    Screen.Cursor := crDefault;
  end;
  memPrueba.Lines.Text := LMensaje;
  if LOk then
    MessageDlg(LMensaje, mtInformation, [mbOK], 0)
  else
    MessageDlg(LMensaje, mtError, [mbOK], 0);
end;

procedure TfrmConfigBascula.btnProbarClick(Sender: TObject);
var
  LCfg: TPesadoConfig;
  LTexto: string;
  LPeso: Double;
  LEstab: Integer;
  LLineas: TStringList;
  I: Integer;
begin
  if not LeerDePantalla(LCfg) then
    Exit;
  if LCfg.Simulado then
  begin
    memPrueba.Lines.Text := 'Modo simulación activo: no se prueba el puerto físico.';
    Exit;
  end;
  memPrueba.Lines.Text := 'Leyendo ' + LCfg.Puerto + '...';
  Screen.Cursor := crHourGlass;
  try
    Application.ProcessMessages;
    ProbarPuertoBascula(LCfg, 3, LTexto);
  finally
    Screen.Cursor := crDefault;
  end;
  memPrueba.Lines.Text := LTexto;

  // Mostrar la interpretación de la última trama
  LLineas := TStringList.Create;
  try
    LLineas.Text := StringReplace(StringReplace(LTexto, '<CR>', '', [rfReplaceAll]), '<LF>', '', [rfReplaceAll]);
    for I := LLineas.Count - 1 downto 0 do
      if ParsearTramaPeso(StringReplace(StringReplace(LLineas[I], '<STX>', '', [rfReplaceAll]), '<ETX>', '', [rfReplaceAll]),
        LCfg.UnidadTrama, LPeso, LEstab) then
      begin
        memPrueba.Lines.Add('');
        memPrueba.Lines.Add(Format('>> Peso interpretado: %.3f kg', [LPeso]));
        Break;
      end;
  finally
    LLineas.Free;
  end;
end;

procedure TfrmConfigBascula.btnGuardarClick(Sender: TObject);
var
  LCfg: TPesadoConfig;
begin
  if not LeerDePantalla(LCfg) then
    Exit;
  FConfig := LCfg;
  FConfig.Guardar;
  ModalResult := mrOk;
end;

class function TfrmConfigBascula.Ejecutar(var AConfig: TPesadoConfig): Boolean;
var
  LForm: TfrmConfigBascula;
begin
  LForm := TfrmConfigBascula.Create(nil);
  try
    LForm.FConfig := AConfig;
    LForm.CargarEnPantalla;
    Result := LForm.ShowModal = mrOk;
    if Result then
      AConfig := LForm.FConfig;
  finally
    LForm.Free;
  end;
end;

end.
