unit Simulator.AssettoCorsa;

// #ToDo1 -oMvR: 2-9-2017: configurable speed for full fan power

interface
uses
  System.Classes,
  Vcl.Controls,
  Vcl.ExtCtrls,
  Vcl.Forms,
  Vcl.StdCtrls,

  Simulator.Base,
  Simulator.Registry, Vcl.Samples.Spin;


type
  TAssettoCorsaFrame = class(TSimulatorBaseFrame)
    SimTimer: TTimer;
    StatusCaptionLabel: TLabel;
    StatusLabel: TLabel;
    CurrentSpeedCaptionLabel: TLabel;
    FanFullSpeedCaptionLabel: TLabel;
    FanFullSpeedUnitsLabel: TLabel;
    FanFullSpeedEdit: TSpinEdit;
    CurrentSpeedLabel: TLabel;

    procedure SimTimerTimer(Sender: TObject);
  public
    procedure Initialize; override;

    procedure Start; override;
    procedure Stop; override;
  end;


implementation
uses
  System.SysUtils,

  AssettoCorsa.SharedMemory;


{$R *.dfm}


{ TAssettoCorsaFrame }
procedure TAssettoCorsaFrame.Initialize;
begin
  inherited Initialize;

  CurrentSpeedLabel.Caption := '';
end;


procedure TAssettoCorsaFrame.SimTimerTimer(Sender: TObject);
var
  gameState: IAssettoCorsaSharedMemory;
  physics: TACSMPhysics;
  fanValue: Integer;

begin
  gameState := GetAssettoCorsaSharedMemory;
  if gameState.GetPhysics(physics) then
  begin
    StatusLabel.Caption := 'Connected';
    CurrentSpeedLabel.Caption := Format('%.0f km/h', [physics.speedKmh]);

    if Fans.Ready then
    begin
      fanValue := Trunc((physics.speedKmh / FanFullSpeedEdit.Value) * 255);
      if fanValue > 255 then
        fanValue := 255;

      Fans.SetAll(fanValue);
    end;

    SimTimer.Interval := 250;
  end else
  begin
    StatusLabel.Caption := 'Assetto Corsa not running';
    CurrentSpeedLabel.Caption := '';
    SimTimer.Interval := 3000;

    if Fans.IsRunning then
      Fans.SetAll(0);
  end;
end;


procedure TAssettoCorsaFrame.Start;
begin
  inherited Start;

  SimTimer.Enabled := True;
end;


procedure TAssettoCorsaFrame.Stop;
begin
  SimTimer.Enabled := False;

  inherited Stop;
end;


initialization
  RegisterSimulator('AssettoCorsa', 'Assetto Corsa',
    function(AFans: ISimulatorFans): ISimulator
    begin
      Result := TSimulatorFrame<TAssettoCorsaFrame>.Create(AFans);
    end);

end.
