unit dlclock;

{$mode objfpc}

interface

uses
  Classes, SysUtils, FileUtil, LResources, Forms, Controls, Graphics, Dialogs,dateutils
  , StdCtrls, ExtCtrls, Grids
  , StrUtils  //AnsiMidStr
  , LazSysUtils //For NowUTC()
  ;

type

  { TForm6 }

  TForm6 = class(TForm)
    DifferenceIndicator: TShape;
    CloseButton: TButton;
    RunningIndicator: TShape;
    Label1: TLabel;
    RunningingStatus: TLabel;
    Memo1: TMemo;
    RunningStatus: TLabel;
    UnitClockText: TLabeledEdit;
    UTCClockText: TLabeledEdit;
    LocalTimeText: TLabeledEdit;
    DifferenceTimeText: TLabeledEdit;
    PauseClockButton: TButton;
    ResumClockButton: TButton;
    SetDeviceClock: TButton;
    Timer1: TTimer;
    procedure CloseButtonClick(Sender: TObject);
    procedure PauseClockButtonClick(Sender: TObject);
    procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
    procedure FormCreate(Sender: TObject);
    procedure FormHide(Sender: TObject);
    procedure FormShow(Sender: TObject);
    procedure ResumClockButtonClick(Sender: TObject);
    procedure SetDeviceClockClick(Sender: TObject);
    procedure Timer1Timer(Sender: TObject);
  private
    { private declarations }
    procedure ExecuteQueue();
  public
    { public declarations }
  end;

var
  Form6: TForm6;

implementation
uses
  Unit1,
  header_utils;
var
  LastUnitTimeString : String = '0';

{ TForm6 }

procedure TForm6.Timer1Timer(Sender: TObject);
{ This timer runs once per second.
  Mostly to update readings from the DL (for now).
  Queued instructions sent here also to avoid collision with timed requests. }
begin
  ExecuteQueue();
end;
procedure TForm6.ExecuteQueue();
var
   pieces: TStringList;
   result: AnsiString;
   ThisMomentLocal, ThisMomentUTC, UnitTime, LastUnitTime: TDateTime;
   ThisMomentLocalString, ThisMomentUTCString, UnitTimeString : String;
   DifferenceTime : Int64;
begin
   Timer1.Enabled:=False;
   pieces := TStringList.Create;
   pieces.Delimiter := ',';

   ThisMomentLocal:=Now();
   ThisMomentUTC:=LazSysUtils.NowUTC();
if (((SelectedModel=model_DL) or (SelectedModel=model_GPS) or (SelectedModel=model_V)or (SelectedModel=model_DLS))) then
   begin
     if DLQueue[0]='SetClock' then
        begin
            DLQueue[0]:='';
            StatusMessage('Setting unit clock...');
            result:=SendGet('LC'+FormatDateTime('yy-mm-dd ',ThisMomentUTC)+IntToStr(DayOfWeek(ThisMomentUTC))+FormatDateTime(' hh:nn:ss',ThisMomentUTC)+'x');
            { TODO 2 : check result }
        end
     else if DLQueue[0]='PauseClock' then
       begin
         DLQueue[0]:='';
         result:=SendGet('Lex');
       end
     else if DLQueue[0]='ResumeClock' then
       begin
         DLQueue[0]:='';
         result:=SendGet('LEx');
       end
     else
        begin
         result:=sendget('Lcx',False,3000,True,True); { Read the RTC, but do not log every reading }
          if Length(result)>=21 then
            begin
              UnitTimeString:=FixDate(AnsiMidStr(Trim(result),4,19));
              UnitClockText.Text:=UnitTimeString;
              try
                 UnitTime:=ScanDateTime('yy-mm-dd hh:nn:ss',LeftStr(UnitTimeString,9)+RightStr(UnitTimeString,8));
                 if (CompareText(LastUnitTimeString,UnitTimeString)=0) then begin //values are the same (unchanged)
                     RunningIndicator.Brush.Color:=clRed;
                     RunningStatus.Caption:='Charging';
                   end
                 else begin //values are different
                   if (CompareText(LastUnitTimeString,'0')=0) then begin
                     RunningIndicator.Brush.Color:=clGray;
                     RunningStatus.Caption:='Reading ...';
                   end
                   else begin
                     RunningIndicator.Brush.Color:=clLime;
                     RunningStatus.Caption:='Running';
                   end
                 end;
                 LastUnitTimeString:=UnitTimeString;
              except
                 StatusMessage('Invalid RTC from device = '+UnitTimeString);
                 UnitTime:=ThisMomentUTC;
              end;
              DifferenceTime:=SecondsBetween(ThisMomentUTC,UnitTime);
              DifferenceTimeText.Text:=IntToStr(DifferenceTime);

              if (abs(DifferenceTime)>2) then begin
                  DifferenceIndicator.Brush.Color:=clRed;
                end
              else begin
                DifferenceIndicator.Brush.Color:=clLime;
              end;

            end
          else begin
            UnitTimeString:='unknown';
            UnitClockText.Text:=UnitTimeString;
          end;
          LocalTimeText.Text:=FormatDateTime('yy-mm-dd ddd hh:nn:ss',ThisMomentLocal);
          UTCClockText.Text:=FormatDateTime('yy-mm-dd ddd hh:nn:ss',ThisMomentUTC);
          end;
     end
   else
       DLRefreshed:=False;

   Timer1.Enabled:=True;


end;

procedure TForm6.FormShow(Sender: TObject);
begin
  DifferenceIndicator.Brush.Color:=clGray;

  {Restart reading clock}
  LastUnitTimeString := '0';

  Application.ProcessMessages;
  ExecuteQueue();
  Timer1.Enabled:=True;
end;

procedure TForm6.ResumClockButtonClick(Sender: TObject);
begin
  DLQueue[0]:='ResumeClock';
end;

procedure TForm6.SetDeviceClockClick(Sender: TObject);
begin
 {****Record current clock offset in history, and the time that this clock was set
 All times shown will be UTC since history may have been recorded from different time zones
 DATESTAMP: Message with details.}
  DLQueue[0]:='SetClock';
end;

procedure TForm6.FormHide(Sender: TObject);
begin
  Timer1.Enabled:=False;
end;

procedure TForm6.FormClose(Sender: TObject; var CloseAction: TCloseAction);
begin
  Timer1.Enabled:=False;
end;

procedure TForm6.PauseClockButtonClick(Sender: TObject);
begin
  DLQueue[0]:='PauseClock';
end;

procedure TForm6.CloseButtonClick(Sender: TObject);
begin
  Form6.Close;
end;

procedure TForm6.FormCreate(Sender: TObject);
begin
   UnitClockText.Font.Name:=FixedFont;
   UTCClockText.Font.Name:=FixedFont;
   LocalTimeText.Font.Name:=FixedFont;
   DifferenceTimeText.Font.Name:=FixedFont;
end;

initialization
  {$I dlclock.lrs}

end.

