unit uEditorUtils;

interface

uses
  uEditorItem, uDADataTable, Controls;

type
  TFuncItemEditor = function(ABizObject : TDADataTableRules) : TModalResult;
  TProcItemEditor = procedure(ABizObject : TDADataTableRules);
  TFuncGetEditor = function : IEditorItem;

  TEditorType = (etItem, etItems, etSelectItems);

procedure RegisterEditor(const IID : TGUID; const AFuncItemEditor : TFuncItemEditor;
  const AType : TEditorType);

function ShowEditor(const IID : TGUID; ABizObject : TDADataTableRules;
  const AType : TEditorType) : TModalResult;


implementation

uses
  Dialogs, Classes, ComObj, SysUtils;

var
  FBizEditorsList : TList;

type
  PBizEditorsRec = ^TBizEditorsRec;
  TBizEditorsRec = record
    IID : String;
    ItemEditor : TFuncItemEditor;
    ItemsEditor : TFuncItemEditor;
    SelectItemsEditor : TFuncItemEditor;
  end;


function FindBizEditors(const IID : TGUID) : PBizEditorsRec;
var
  P: PBizEditorsRec;
  I: Integer;
  AIID : String;
begin
  Result := NIL;
  AIID := GUIDToString(IID);
  if FBizEditorsList <> nil then
    for I := 0 to FBizEditorsList.Count-1 do
    begin
      P := FBizEditorsList[I];
      if (AIID = P^.IID) then
      begin
        Result := P;
        Break;
      end;
    end;
end;

procedure RegisterEditor(const IID : TGUID; const AFuncItemEditor : TFuncItemEditor;
  const AType : TEditorType);
var
  P: PBizEditorsRec;
begin
  P := NIL;
  if FBizEditorsList = nil then
    FBizEditorsList := TList.Create;

  P := FindBizEditors(IID);
  if not Assigned(P) then
    New(P);
  try
    P^.IID := GUIDToString(IID);
    case AType of
      etItem          : P^.ItemEditor := AFuncItemEditor;
      etItems         : P^.ItemsEditor := AFuncItemEditor;
      etSelectItems   : P^.SelectItemsEditor := AFuncItemEditor;
    end;
    FBizEditorsList.Insert(0, P);
  except
    on E: EConvertError do
      ShowMessage(E.Message);
  end;
end;

function ShowEditor(const IID : TGUID; ABizObject : TDADataTableRules;
  const AType : TEditorType) : TModalResult;
var
  P: PBizEditorsRec;
begin
  P := FindBizEditors(IID);

  if Assigned(P) then
    case AType of
      etItem          : Result := P.ItemEditor(ABizObject);
      etItems         : Result := P.ItemsEditor(ABizObject);
      etSelectItems   : Result := P.SelectItemsEditor(ABizObject);
    end;
end;


initialization
  FBizEditorsList := TList.Create;

finalization
  FBizEditorsList.Free;

end.
