program ReflectionUpdater;
var
  MainMenuItem, MenuCheck, MenuUpdate,AutoUpdate : TMenuItem;
  started: Boolean;
  Timer : TTimer;
  Updating : boolean;
  LocalR,OnlineR: Integer;

  F: TForm;
  Memo: TMemo;
  but: TButton;


function GetNumbers(const str : string) : string;
var
  i : integer;
begin;
  for i := 1 to length(str) do
    case str[i] of
      '0'..'9': result := result + str[i];
    end;
end;
  
procedure GetOnlineVersion(out RefVersion : integer);
begin
  RefVersion := strtointdef(GetNumbers(getpage('http://wizzup.org/static/srl/srl_refl_version')),-1);
end;

procedure GetLocalVersion(out RefVersion : integer);
begin
  RefVersion := StrToIntDef(Settings.GetKeyValueDef('RefVersion','-1'),-1);
end;


function UpdateRef: boolean;
var
  Contents : String;
  DeContents : string;
  Failed : boolean;
begin
    Memo.Lines.Add('Downloading Reflection...');
    Contents := GetPage('http://wizzup.org/static/srl/srlref.tar.bz2');
    Failed := True;
    Memo.Lines.Add('Uncompressing Reflection...');
    if DecompressBZip2(Contents,DeContents,4096) then
      if UnTarEx(DeContents,IncludePath,true) then
        Failed := False;
    if not Failed then
      Settings.SetKeyValue('RefVersion',inttostr(OnlineR));
    if Result then
      Result := Failed;
    if not Failed then
  begin
    Memo.Lines.Add('Succesfully updated your Reflection!');
      Writeln('Succesfully updated your Reflection!');
  end;
end;

procedure DoUpdate(Sender: TObject);
begin
  if LocalR < OnlineR then
  begin
    Memo.Lines.Add('Reflection update. Old version: ' + IntToStr(LocalR) +
                   ' New version: ' + IntToStr(OnlineR));
    UpdateRef;
  end;
  F.ModalResult := mrOk;
end;


function Update : boolean;
var
   OpenForm: Boolean;
begin
  Result := false;
  if Updating then
    Exit;
  Updating := True;

  if (LocalR < OnlineR) then
  begin
       case MessageDlg('Reflection Updater', 'Updates are available. '+
                      'Do you want to open the Updater now?',
                      mtConfirmation, [mbNo,mbYes],0) of
           mrYes : OpenForm := True;
      else
           OpenForm := False;
      end;
    if not OpenForm then
    begin
      Updating := False;
      Exit;
    end;
    Result := True;
    f.ShowModal;
  end else
  begin
    writeln('No Reflection update');
  end;

  Updating := False;

end;

procedure OnReflectionCheckClick(Sender: TObject);
var
  LocalR,OnlineR : integer;
begin
  GetLocalVersion(LocalR);
  GetOnlineVersion(OnlineR);

  if (LocalR < OnlineR) then
  begin
    Writeln('A new Reflection version is available');
    Update;
  end;
end;

procedure SetAutoUpdate(Sender: TObject);
begin
  AutoUpdate.Checked := not AutoUpdate.Checked;
  Timer.Enabled := AutoUpdate.Checked;
  if LowerCase(Settings.GetKeyValueDef('AutoUpdate','True')) = 'true' then
    Settings.SetKeyValue('AutoUpdate', 'False')
  else
    Settings.SetKeyValue('AutoUpdate', 'True');
end;

procedure OnReflectionUpdateClick(Sender: TObject);
begin
  GetLocalVersion(LocalR);
  GetOnlineVersion(OnlineR);

  if (OnlineR <= LocalR) then
    MessageDlg('Reflection Updater', 'No Reflection update' ,mtConfirmation, [mbYes],0)
  else
    Update;
end;

procedure OnUpdateTimer(Sender: TObject);
begin;
  Timer.Interval := 30 * 60 * 1000; //Every half hour
  GetLocalVersion(LocalR);
  GetOnlineVersion(OnlineR);
  Update;
end;

procedure Init;
begin;
  MainMenuItem := TMenuItem.Create(Simba_MainMenu);  
  MainMenuItem.Caption := 'Reflection';
  Simba_MainMenu.Items.Add(MainMenuItem);

  MenuCheck := TMenuItem.Create(MainMenuItem);
  MenuCheck.Caption := 'Check for new Reflection';
  MenuCheck.OnClick := @OnReflectionCheckClick;
  MainMenuItem.Add(MenuCheck);

  MenuUpdate := TMenuItem.Create(MainMenuItem);
  MenuUpdate.Caption := 'Update Reflection';
  MenuUpdate.OnClick := @OnReflectionUpdateClick;
  MainMenuItem.Add(MenuUpdate);

  AutoUpdate := TMenuItem.Create(MainMenuItem);
  AutoUpdate.Caption := 'Automatically update';
  AutoUpdate.OnClick := @SetAutoUpdate;
  AutoUpdate.Checked := LowerCase(Settings.GetKeyValueDef('AutoUpdate','True')) = 'true';
  MainMenuItem.Add(AutoUpdate);
 
  Timer := TTimer.Create(Simba);
  Timer.Interval := 5000;
  Timer.OnTimer := @OnUpdateTimer;
  Timer.Enabled :=AutoUpdate.Checked;

  F := TForm.Create(nil);
  With F Do
    begin
      Visible := False;
      Width := 300;
      Height := 300;
      BorderStyle := bsSingle;
      Caption := 'Reflection Updater - Updates Available';
    end;

  but := TButton.Create(F);

  with but do
    begin
      Parent := F;
      Left := 10;
      Top := 10;
      Caption := 'Update';
      Width := 280;

      OnClick := @DoUpdate;
    end;

  Memo := TMemo.Create(F);

  with Memo do
    begin
      Parent := F;
      Left := 10;
      Top := 40;
      Width := 280;
      Height := 250;
    end;

  started := True;
end;

procedure Free;
begin
  if (started) then
     Timer.Enabled := False;//Freeing the components is not needed, as they will be freed upon the freeing of Simba.
{  if F <> nil then
    F.Free; }
end;

procedure Attach;
begin;
  Writeln('From now on, you shall be alerted as to when your Reflection is out of date!');
  MainMenuItem.Visible := True;
  Timer.Enabled := AutoUpdate.Checked;
end;

Procedure Detach;
begin
  Timer.Enabled := False;
  MainMenuItem.Visible := False;
end;

function GetName : string;
begin;
  result := 'Reflection Updater';
end;

function GetVersion : string;
begin;
  result := '1.0';
end;

begin
end.
