unit datreplacedates;

{$mode ObjFPC}{$H+}

interface

uses
  Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, StdCtrls,
  Buttons, ComCtrls, ExtCtrls
  , LazFileUtils //required for ExtractFileNameOnly
  ;

type

  { TForm9 }

  TForm9 = class(TForm)
    MinuteEdit: TLabeledEdit;
    Memo1: TMemo;
    OpenDialog1: TOpenDialog;
    SourceFileButton: TBitBtn;
    SourceFileEdit: TEdit;
    StartButton: TButton;
    StatusBar1: TStatusBar;
    procedure SourceFileButtonClick(Sender: TObject);
    procedure StartButtonClick(Sender: TObject);
  private

  public

  end;

var
  Form9: TForm9;

implementation
uses
  Unit1
  , strutils
  , appsettings
  , dateutils //Required to convert logged UTC string to TDateTime
  ;
var
  SourcePathFile:String;
  subfix: ansistring; //Used for time zone conversions

{ TForm9 }

procedure TForm9.SourceFileButtonClick(Sender: TObject);
begin
  OpenDialog1.InitialDir:=RemoveMultiSlash(appsettings.LogsDirectory);
  if OpenDialog1.Execute then begin
    SourcePathFile:=OpenDialog1.FileName;
    SourceFileEdit.Text:=SourcePathFile;
  end;
end;

{ Convert file and write to the outputfile.}
procedure TForm9.StartButtonClick(Sender: TObject);
{ Stages:
 0 = reading and writing untouched initial header lines.
 1 = reading and writing untouched first timestamp.
 2 = writing replaced timestamps
}
Var
      Infile: TStringList;
      pieces: TStringList;
      OutFile: TextFile;
      ComposeString: String;
      OutputPathFileName, SourceFileName:String;
      WorkingPath, OutputPath:String;
      WriteAllowable: Boolean = True; //Allow output file to be written or not.
      s: String; //Temporary string
      i:Integer;//Counter
      stage:Integer=0; //Stage of processing

      UTCRecord :TDateTime;
      LocalRecord :TDateTime;

      IntervalTime: Integer = 5; //Time between consecutive datestamps

  Begin
    Infile := TStringList.Create;
    pieces := TStringList.Create;

    SourceFileName:=SourcePathFile;
    WorkingPath:=RemoveMultiSlash(SourcePathFile + DirectorySeparator);
    OutputPath:=ExtractFilePath(SourcePathFile);
    OutputPathFileName:=RemoveMultiSlash(WorkingPath+'JDUTDEC' + DirectorySeparator);

    { So far there are no conditions to prevent writing files.
      The output directory either already exists, or has been created.
      The output files will overwrite previous output files.}
    WriteAllowable:=True;

    if WriteAllowable then begin

    { Process the file }

    try

        {Start reading file.}

        { Define Input file. }
        SourceFileName:= ExtractFileName(SourcePathFile);

        { Define Output file. }
        OutputPathFileName:=OutputPath+LazFileUtils.ExtractFileNameWithoutExt(SourceFileName)+'_DatesReplaced.dat';
        AssignFile(OutFile, OutputPathFileName);
        Rewrite(OutFile); //Open file for writing

        {$I+}
        try

           StatusBar1.Panels.Items[0].Text:='Reading Input file';

           Infile.LoadFromFile(OpenDialog1.Filename);

           pieces.Delimiter := ';';
           pieces.StrictDelimiter := True; //Do not parse spaces

           IntervalTime:= StrToIntDef(MinuteEdit.Text,5);

            {Go through all lines in input file}
            for s in Infile do begin

              // read records to modify time stamp
              if (stage=2) then begin
                 { Separate the fields of the record. }
                 pieces.DelimitedText := s;

                 //Add the prescribed time for the new record
                 UTCRecord:=IncMinute(UTCRecord, IntervalTime);
                 LocalRecord:=IncMinute(LocalRecord, IntervalTime);

                 { Compose the output string.}
                 ComposeString:=
                   FormatDateTime('yyyy-mm-dd"T"hh:nn:ss.zzz";"',UTCRecord) +
                   FormatDateTime('yyyy-mm-dd"T"hh:nn:ss.zzz',LocalRecord);

                 { Compose remainder of string untouched. }
                 for i:=2 to pieces.count-1 do begin
                   ComposeString:=ComposeString+';'+pieces.Strings[i];
                 end;

                 { Write modified record to output file. }
                 WriteLn(OutFile,ComposeString);
              end;

              { Read initial record. }
               if (stage=1) then begin
               { Separate the fields of the record. }
                 pieces.DelimitedText := s;
                 UTCRecord:=ScanDateTime('yyyy-mm-dd"T"hh:nn:ss.zzz',pieces.Strings[0]); { Read initial UT time. }
                 LocalRecord:=ScanDateTime('yyyy-mm-dd"T"hh:nn:ss.zzz',pieces.Strings[1]); { Read initial Local time. }
                 WriteLn(OutFile,s); { Write untouched record to output file. }
                 stage:=2;
               end;

                { Write untouched lines to output file. }
                if (stage=0) then begin
                   WriteLn(OutFile,s);
                  if AnsiContainsStr(s,'# END OF HEADER') then begin
                    stage:=1;
                  end;
                end;

             end;


           Flush(OutFile);
           CloseFile(OutFile);

           StatusBar1.Panels.Items[0].Text:='Finished file'+SourceFileName;

         except
           on E: EInOutError do
           begin
            MessageDlg('Error', 'File handling error occurred. Details: '+E.ClassName+'/'+E.Message, mtError, [mbOK],0);
           end;
         end;


    StatusBar1.Panels.Items[0].Text:='Finished converting file. Result stored in :'+OutputPath;


    finally
    end;

end;

  end;

initialization
  {$I datreplacedates.lrs}

end.

