unit Sidebar;

interface
uses
  Controls,
  AdvPageControl,
  Dialogs,
  Forms,
  Classes,
  ScadaBase;

  procedure addSidebar(name: string; cls: TFormClass);
  function  showSidebar(obj: TCustomScadaObject): Boolean;
  procedure updateSidebar;
  function getSidebarObject: TCustomScadaObject;
  procedure hideSidebar;

implementation
uses
  ControlPanel,
  RpVisualGlobal,
  RpVisualUtils,
  main;

var
  list: TStringList = nil;
  current: TForm = nil;
  scadaObject: TCustomScadaObject = nil;



procedure addSidebar(name: string; cls: TFormClass);
var
  form: TForm;
begin
  if list = nil then begin
    list := TStringList.Create;
    list.Sorted := True;
    list.Duplicates := dupIgnore;
  end;

  form := cls.Create(Form1);
  list.AddObject(name, form);

end;



function showSidebar(obj: TCustomScadaObject): Boolean;
var
  found: TForm;
  i: integer;
begin
  Result := false;
  if (obj.Sidebar = '') or (not list.Find(obj.Sidebar, i)) then begin
    HideSidebar;
    Exit;
  end;

  found := TForm(list.Objects[i]);
  if (current <> nil) and (current <> found) then
    hideSidebar;

  if current = nil then
    current := found;

  scadaObject := obj;
  SetPathRootScadaObjects(current, obj.TagPath, obj.TagRoot);

  current.Parent := Form1;
  current.Left := Form1.Width - current.Width;
  current.Top := Form1.PageControl.Top;
  current.Height := Form1.PageControl.Height;
  current.Anchors := [akRight, akTop, akBottom];
  current.FormStyle := fsStayOnTop;
  current.BorderStyle := bsNone;


  if Assigned(current.OnActivate) then
    current.OnActivate(nil);

  Form1.PageControl.Align := alNone;
  if Mouse.CursorPos.x > ((Form1.Width div 13)*9) then begin
    Form1.PageControl.Left := -current.Width+8;
  end;

  if Mouse.CursorPos.x < (Form1.Width div 4) then begin
    Form1.PageControl.Left := 0;
  end;

  current.show;


  Result := true;
end;

function getSidebarObject: TCustomScadaObject;
begin
  result := scadaObject;
end;


procedure updateSidebar;
begin
  if current <> nil then
    CustomScanScadaObjects(current, UpdateDeviceProc);
end;


procedure hideSidebar;
begin
  if current <> nil then begin
    current.Hide;
    current.Parent := nil;
    current := nil;
    scadaObject := nil;
  end;
end;



procedure clear;
begin
  if list = nil then
    Exit;

  list.Free;
  list := nil;
end;


initialization

finalization
  clear();

end.
