@echo off
setlocal disableDelayedExpansion

:Variables
set InputFile=%2
set OutputFile=%InputFile%#
set entity=%1
set filtername=%4
set "_strFind=//----Check_GetEntity%3"
set "_strInsert1=        public async Task Check_Get%entity%%3()"
set "scripts_path=%~dp0..\Core"
set templatefile_path=%scripts_path%\Entity%3_test.tmpl


rem if already inserted, do nothing
:Check
for /F "delims=" %%L in ('findstr /n "^" "%InputFile%"') do (
  set "line=%%L"
  setlocal EnableDelayedExpansion

  set "line=!line:*:=!"
  if "!line!" neq "" (
    set "_line=!line:%_strInsert1%=!"
  ) else (
    set _line=!line!
  )
  if "!_line!" neq "!line!" goto finish
  endlocal
)

call %scripts_path%\replaceinfile.bat %templatefile_path% _entity_ %entity% dontdelete>nul
if "%filtername%" neq "" (
  call %scripts_path%\replaceinfile.bat %templatefile_path%# _filter_ %filtername% dontdelete>nul
  del %templatefile_path%# >nul
  copy %templatefile_path%## %templatefile_path%# >nul
  del %templatefile_path%## >nul
)

:Replace
>"%OutputFile%" (
  for /F "delims=" %%L in ('findstr /n "^" "%InputFile%"') do (
    set "line=%%L"
    setlocal EnableDelayedExpansion

    set "line=!line:*:=!"
    if "!line!" neq "" (
      set "_line=!line:%_strFind%=!"
    ) else (
      set _line=!line!
    )


    echo.!line!
    if "!_line!" neq "!line!" (
           type %templatefile_path%#
    )
    endlocal
  )
)

del %templatefile_path%# >nul
del %InputFile% >nul
copy %OutputFile% %InputFile% >nul
del %OutputFile% >nul
:finish