program udmc;

{$mode objfpc}{$H+}

uses
  {$IFDEF UNIX}{$IFDEF UseCThreads}
  cthreads,
  {$ENDIF}{$ENDIF}
  Classes
  , SysUtils
  , CustApp
  , cli_utils
  , dateutils
  ;

{ Tudmc }
type Tudmc = class(TCustomApplication)
  protected
    procedure DoRun; override;
  public
    constructor Create(TheOwner: TComponent); override;
    destructor Destroy; override;
    procedure WriteHelp; virtual;
  end;


procedure Tudmc.DoRun;
var
  ErrorMsg: String;
  serialnumber: string;
  DelayInSeconds: Integer=60;//Drfault delay of 60 seconds
  RemainingSeconds: Integer;
  RunWhile:Boolean=True;
begin

  // quick check parameters
  ErrorMsg:=CheckOptions('hr',['help','read','log','LCM:','LCMS:','LCMM:','SUI:','v:']);
  if ErrorMsg<>'' then begin
    ShowException(Exception.Create(ErrorMsg));
    Terminate;
    Exit;
  end;

  // parse parameters
  if HasOption('h','help') then begin
    WriteHelp;
    Terminate;
    Exit;
  end;

  //Verbose mode
  if HasOption('v') then begin
    verbosity:=StrToInt64Def(GetOptionValue('v'),1);
  end;

  //Serial number defined
  if HasOption('SUI') then begin
    serialnumber:=GetOptionValue('SUI');
    cli_utils.FindUSBtty(serialnumber);
  end;

  //Log
  if HasOption('l','log') then begin
    verbose(verbose_debug,'HasOption l log');
    WriteDLHeader('');
  end;

  if HasOption('LCMS') then begin
    LCMode:='LCMS';
    LCFreq:=StrToIntDef(GetOptionValue('LCMS'),1);
    DelayInSeconds := LCFreq; //Store every x seconds
  end;

  if HasOption('LCMM') then begin
    LCMode:='LCMM';
    LCFreq:=StrToIntDef(GetOptionValue('LCMM'),1);
    DelayInSeconds := LCFreq*60; //Store every x seconds
  end;

  if HasOption('LCM') then begin //Set delay
    verbose(verbose_debug,'HasOption LCM');
    LCMode:='LCM';
    LCFreq:=StrToIntDef(GetOptionValue('LCM'),1);
    DelayInSeconds := 1; //Store every x seconds **must be fixed for specific mode**
  end;


  if HasOption('r','read') then begin  //Read once
      verbose(verbose_debug,'HasOption r read');
      cli_utils.FindUSBtty(serialnumber);
      writeln(SendGet('rx'));
    end
  else begin   //Perform logging if not "read once" mode
    verbose(verbose_action,'Perform logging if not "read once" mode');
    cli_utils.FindUSBtty(serialnumber);
    if not (SelectedPort='') then begin
      WriteDLHeader('');
      LogOneReading(); //Store first reading

      RemainingSeconds:= DelayInSeconds;
      verbose(verbose_action,'Perform continuous logging every '+IntToStr(DelayInSeconds)+' seconds.');
      while RunWhile do begin //Waking up once per second
             sleep(1000 - MilliSecondOf(Now));
             Dec(RemainingSeconds);
             if RemainingSeconds<=0 then begin
                LogOneReading(); //Store successive readings
                RemainingSeconds:= DelayInSeconds; //Reset delay
             end;
       end;
     end;
  end;


  // stop program loop
  Terminate;
end;

constructor Tudmc.Create(TheOwner: TComponent);
begin
  inherited Create(TheOwner);
  StopOnException:=True;
end;

destructor Tudmc.Destroy;
begin
  inherited Destroy;
end;

procedure Tudmc.WriteHelp;
begin
  { add your help code here }
  writeln('Usage: ',ExeName,' -h');
  WriteLn('--SUI=FT345678      to specifiy the USB ID Ex.: FT345678');
  WriteLn('   default to last USB SQM found');
  WriteLn('-r | --read   to read once only');
  WriteLn('--log');
  //WriteLn('--LCM=n n=mode');
  WriteLn('--LCMS=n            where n=seconds');
  //WriteLn('--LCMM=n n=minutes');
  WriteLn('--v=n  where n =');
  WriteLn('     1 for errors only');
  WriteLn('     2 for actions');
  WriteLn('     3 debugging information');
end;


var
  Application: Tudmc;
{$R *.res}


begin
  Application:=Tudmc.Create(nil);
  Application.Title:='Unihedron Device Manager command line';
  Application.Run;
  Application.Free;
end.

