unit ufAuto;
{$INCLUDE 'Filters.inc'}

interface

uses
  SysUtils, Classes,
  uFilter;

type
  TFilterAutoSelect = class(TFilter)
  protected
    function FindFilter(const FileName, Content: string): TFilter;
  public
    class function ID: string; override;
    class function Name: string; override;
    class function Priority: TFilter.TPriority; override;
    procedure Clear; override;
    function IsSupported(const FileName, Content: string): boolean; override;
    function Execute(const FileName, Content: string): string; override;
  end;

implementation

uses
  Windows,
  {$INCLUDE 'DelphiFarUnits.inc'} ,
  uPlugin,
  uSystem, uStrings, uMessages;

{ TFilterAutoSelect }

procedure TFilterAutoSelect.Clear;
begin
  inherited;
  Description := GetMsg(MFilterAutoSelectDescription);
end;

function TFilterAutoSelect.Execute(const FileName, Content: string): string;
var
  Filter: TFilter;
begin
  Filter := FindFilter(FileName, Content);
  if Filter = nil then
    raise EFilterError.Create(GetMsg(MNoApplicableFilterFound));
  if Filter.EditBeforeUse then
  begin
    if not Filter.ConfigureBeforeUse then
      Abort;
  end;
  Result := Filter.Execute(FileName, Content);
end;

function TFilterAutoSelect.FindFilter(const FileName, Content: string): TFilter;
var
  FilterList: TFilterList;
  i: integer;
begin
  Result := nil;
  FilterList := (TFarPlugin.Instance as TPlugin).CreateFilterList(True);
  try
    for i := 0 to Pred(FilterList.Count) do
    begin
      if not (FilterList[i] is TFilterAutoSelect) then
      begin
        if FilterList[i].IsSupported(FileName, Content) then
        begin
          Result := FilterList[i].Clone;
          Break;
        end;
      end;
    end;
  finally
    FreeAndNil(FilterList);
  end;
end;

class function TFilterAutoSelect.ID: string;
begin
  Result := 'auto';
end;

function TFilterAutoSelect.IsSupported(const FileName, Content: string): boolean;
var
  Filter: TFilter;
begin
  Result := False;
  Filter := FindFilter(FileName, Content);
  if Filter <> nil then
    Result := True;
end;

class function TFilterAutoSelect.Name: string;
begin
  Result := GetMsg(MFilterAutoSelectName);
end;

class function TFilterAutoSelect.Priority: TFilter.TPriority;
begin
  Result := prHigh;
end;

initialization
  TRegisteredFilters.Add(TFilterAutoSelect);

end.
