unit DBQRCode;

{$mode objfpc}{$H+}

interface

uses
  Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, QRCode, DbCtrls, db;

type

  { TDBQRCode }

  TDBQRCode = class(TCustomQRCode)
  private
    FDataLink: TFieldDataLink;
    procedure DataChange(Sender: TObject);
    function GetDataField: string;
    function GetDataSource: TDataSource;
    function GetField: TField;
    procedure SetDataField(AValue: string);
    procedure SetDataSource(AValue: TDataSource);
  protected
    procedure Notification(AComponent: TComponent; Operation: TOperation); override;
    function GetText: string; override;
  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
    property Field: TField read GetField;
  published
    property DataField: string read GetDataField write SetDataField;
    property DataSource: TDataSource read GetDataSource write SetDataSource;
  end;

procedure Register;

implementation

procedure Register;
begin
  {$I dbqrcode_icon.lrs}
  RegisterComponents('Data Controls',[TDBQRCode]);
end;

{ TDBQRCode }

procedure TDBQRCode.DataChange(Sender: TObject);
begin
  RemakeQR;
end;

function TDBQRCode.GetDataField: string;
begin
  Result := FDataLink.FieldName;
end;

function TDBQRCode.GetDataSource: TDataSource;
begin
  Result := FDataLink.DataSource;
end;

function TDBQRCode.GetField: TField;
begin
  Result := FDataLink.Field;
end;

procedure TDBQRCode.SetDataField(AValue: string);
begin
  FDataLink.FieldName := AValue;
end;

procedure TDBQRCode.SetDataSource(AValue: TDataSource);
begin
  ChangeDataSource(Self,FDataLink, AValue);
end;

procedure TDBQRCode.Notification(AComponent: TComponent; Operation: TOperation);
begin
  inherited Notification(AComponent, Operation);
  if (Operation=opRemove) then
  begin
    if (FDataLink<>nil) and (AComponent=DataSource) then
      DataSource:=nil;
  end;
end;

function TDBQRCode.GetText: string;
begin
  if Assigned(Field) then
    Result:=Field.AsString
  else
    Result:='';
end;

constructor TDBQRCode.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);
  FDataLink := TFieldDataLink.Create;
  FDataLink.Control := Self;
  FDataLink.OnDataChange := @DataChange;
end;

destructor TDBQRCode.Destroy;
begin
  FDataLink.Destroy;
  inherited Destroy;
end;

end.
