program jasshelper;

{$R 'grammar.res' 'grammar.rc'}

uses
  Forms,
  SysUtils,
  Windows,
  Tlhelp32,
  gErrors in 'gErrors.pas' {Form4},
  about in 'about.pas' {Aboutdialog},
  progress in 'progress.pas' {Form5},
  grimjhconfp in 'grimjhconfp.pas' {grimjhconf},
  warlockerror in 'warlockerror.pas' {Form2},
  storm,
  vxFilesys,
  winexec,
  jasshelperConfigFile,
  Preprocessor,
  Structs,
  JASSerException,
  ExternalUsage,
  JHParams,
  JHInterface,
  Inliner,
  ReturnFix,
  ShadowHelper,
  ImportPaths,
  cUnit,
  jhErrors,
  Constants;

{$R *.res}

//==============================================================================
procedure DialogDoAbout;
var
 a:TAboutDialog;
begin
   a:=TaboutDialog.Create(nil);
   a.ShowWEWarlock(false);
   a.ShowModal;
   a.Destroy;
end;

//==============================================================================
procedure DialogHandleException(const prefix:string; const e:Exception);
begin
  MessageBox(0,pchar(e.message),pchar(prefix),MB_TOPMOST+MB_ICONERROR);
  Halt(1);
end;

//==============================================================================
//  appends suffix to a file name before file extension
//==============================================================================
function GetSuffixedName(x,suf:string):string;
var
   i,L:integer;
begin
    L:=Length(x);
    i:=L;
    while (i>0) do begin
        if (x[i]='.') then begin
            Result:=Copy(x,1,i-1)+suf+Copy(x,i,L-i+1);
            exit;
        end;
        i:=i-1;
    end;
    Result:=x+suf;
end;

//==============================================================================
{*
function doWEWarlock(const m:string):boolean;
var
  f1:string;
  f2,f3,compiled,backup,dir:string;
  i:integer;
begin
   result:=false;
   if (WEWARLOCK_PATH='') then Exit; //it could be that the user wants to run wewarlock himself?

   if (not FileExists(WEWARLOCK_PATH)) then begin
       MessageBox(0, pchar('File does not exist: '+WEWARLOCK_PATH), 'JASSHelper - Error' , MB_YESNOCANCEL    );
   end;

    try
       ProStatus('Executing WEWarlock ...');

       compiled:=GetSuffixedName(m,'_compiled');
       backup:=m+'.beforewewarlock';

      f1:=TempFile;
      f2:=TempFile;
      f3:=TempFile;
      DeleteFile(pchar(GetSuffixedName(m,'_compiled')));
      dir:=ExtractFileDir(WEWARLOCK_PATH);
      i:= WinExec.StartApp(
      WEWARLOCK_PATH,
      '"'+m+'"',dir,0,f3,f1,f2);
      if i > 0 then begin
          if (dir[Length(dir)]<>'\') then dir:=dir+'\';
          warlockerror.ShowError(f1,dir+'WarlockCompiler.exe.stderr.txt',true);
          result:=true;
      end else if i < 0 then begin
         MessageBox(0, pchar('Unable to call : '+WEWARLOCK_PATH), 'Error' , MB_YESNOCANCEL    );
      end else begin
          DeleteFile(pchar(backup));
          MoveFile(pchar(m),pchar(backup ));
          MoveFile(pchar(compiled),pchar(m));
      end;
      ProEnd();
    except
    on e:Exception do begin
        MessageBox(0, pchar(e.Message), 'doWEWarlock Error' , MB_YESNOCANCEL);
        result:=true;
    end;
    end;
end;
*}

//==============================================================================
{*
procedure DialogDoRequire;
begin
    if(JHVariables.SCRIPT_MODE) then raise Exception.Create('//! require found, but --scriptonly is in use');
    storm.MpqAddFileToArchiveEx(mpq,pchar(compiled),'war3map.j',MAFA_REPLACE_EXISTING+MAFA_COMPRESS,MAFA_COMPRESS_DEFLATE,Z_BEST_COMPRESSION);
    storm.MpqCloseUpdatedArchive(mpq,0);
    if dowewarlock(map) then begin
        raise Exception.Create('There were errors while running wewarlock');
    end;
    mpq:=MpqOpenArchiveForUpdate(pchar(map),MOAU_OPEN_EXISTING + MOAU_MAINTAIN_LISTFILE,0);
    storm.MPQExtractFileTo(mpq,'war3map.j',pchar('logs\currentmapscript.j'));
end;
*}

//==============================================================================
procedure WarnAboutExternal();
var msg:string;
begin
    msg := 'To make this warning disappear:'+CRLF;
    msg := msg + '   1. Close your map. (Ctrl-W)'+CRLF;
    msg := msg + '   2. Reopen your map. (Ctrl-O)'+CRLF;
    msg := msg + '   3. Disable all //! external lines'+CRLF;
    msg := msg + '   4. Save your map again. (Ctrl-S)';
  MessageBox(0,pchar(msg),pchar('WARNING: //! external directives used!'),MB_TOPMOST+MB_ICONWARNING);
end;

//==============================================================================
//  BEGIN
//==============================================================================
begin
  try
    //-------------------------------------------
    cUnit.DoAbout := DialogDoAbout;
    //cUnit.DoRequire := DialogDoRequire;
    jhErrors.HandleException := DialogHandleException;
    Application.Initialize;
    Application.Run;

    cUnit.Main(); // <--------<<
    
    if usedExternal then begin
      WarnAboutExternal();
    end;

    if(JHParams.GetRequireCount()>0) then begin
          MessageBox(0,pchar('WEWarlock is no longer supported!'),pchar('//! require directive(s) ignored!'),MB_TOPMOST+MB_ICONWARNING);
    end;

    //-------------------------------------------
  except on e:Exception do
    begin
      jhErrors.HandleException('Unexpected Code Exception!', e);
    end;
  end;  // end of try
end.
