unit Favorites;

{ Global variables }
var
  Favorites: TMenuItem;
  FavoritesAdd: TMenuItem;

const
  FavoritesCfg = 'Favorites.cfg';

  
procedure InitFavorites;
begin
  Favorites := nil;
  UpdateFavorites;
end;

procedure UpdateFavorites;
var
  FavFile: string;
  Favs: TStringList;
  i: Integer;
  TmpItem: TMenuItem;
begin
{ function NewItem(const ACaption: string; AShortCut: TShortCut; AChecked, AEnabled: Boolean; AOnClick: TNotifyEvent; hCtx: Word; const AName: string): TMenuItem; }
  if Favorites = nil then
  begin
    Favorites := NewItem('Favori&tes', 0, False, True, 0, nil {ignored - always must be nil}, 'miFavorites');
    Favorites.OnClick := FavoritesClick;
    MainWindow.Menu.Items.Insert(MainWindow.Menu.Items.Count - 1, Favorites);
  end;
  while Favorites.Count > 0 do
    Favorites.Items[0].Free;
  FavoritesAdd := NewItem('Add current file', 0, False, True, 0, 0, 'miFavoritesAdd');
  FavoritesAdd.OnClick := FavoritesAddClick;
  Favorites.Add(FavoritesAdd);
  FavFile := WorkingDir + FavoritesCfg;
  if FileExists(FavFile) then
  begin
    Favs := TStringList.Create;
    try
      Favs.LoadFromFile(FavFile);
      for i := 0 to Favs.Count - 1 do
        if FileExists(Favs.Strings[i]) then
        begin
          TmpItem := NewItem(Favs.Strings[i], 0, False, True, 0, 0, '');
          TmpItem.OnClick := FavoriteClick;
          Favorites.Add(TmpItem);
        end;
      if Favorites.Count > 1 then
        Favorites.Insert(1, NewLine);
    finally
      Favs.Free;
    end;
  end;
end;

procedure FavoritesClick(Sender: TObject);
var
  i: Integer;
begin
//  Favorites.Caption := 'F1';
  FavoritesAdd.Caption := 'Add Current File';
  for i := 2 to Favorites.Count - 1 do
    if ANSICompareText(Editor.FileName, Favorites.Items[i].Caption) = 0 then
    begin
      FavoritesAdd.Caption := 'Remove Current File';
      break;
    end; 
end;

procedure FavoriteClick(Sender: TObject);
begin
 // ShowMessage(TMenuItem(Sender).Caption);
  Editor.CheckSave;
  Editor.FileOpen(ReplaceString(TMenuItem(Sender).Caption, '&', ''));
end;

procedure FavoritesAddClick(Sender: TObject);
var
  FavFile: string;
  Favs: TStringList;
  i: Integer;
begin
  FavFile := WorkingDir + FavoritesCfg;
  Favs := TStringList.Create;
  try
    if FileExists(FavFile) then
      Favs.LoadFromFile(FavFile);
    if Favs.IndexOf(Editor.FileName) = -1 then
      Favs.Add(Editor.FileName) else
      Favs.Delete(Favs.IndexOf(Editor.FileName));
    Favs.SaveToFile(FavFile);
    UpdateFavorites;
  finally
    Favs.Free;
  end;
end;


end.
