@echo off

if [%1]==[] goto usage
for %%i in ("%~1") do (
    set "FILENAME=%%~ni"
    set "EXT=%%~xi"
    set "DIR=%%~dpi"
)
call C:\kabellaengen\bin\setenv.bat

REM echo Dateiname ohne Erweiterung: %FILENAME%
REM echo Erweiterung: %EXT%
REM echo Verzeichnis: %DIR%
REM 
REM Namen der Zwischenergebnis Dateien
set JSON_POS=%FILENAME%_positionsdraw.json
set JSON_TODRAW=%FILENAME%_todraw.json
REM Namen der Ergebnisdateien
set ERROR_DOUBLE=%FILENAME%_errors.json
set EXCEL_RES=%FILENAME%_cables.xlsx
set DXF_RES=%FILENAME%_cables.dxf

if exist "%~dp0_setenv.bat" (
    echo Lade lokale Umgebungseinstellungen aus _setenv.bat...
    call "%~dp0_setenv.bat"
)
REM Zielverzeichnis
set TARGET_DIR=%PROJECT_BOM_RESULTS%\%FILENAME%
mkdir "%TARGET_DIR%"
REM lösche alte Fehlermeldungen
del "%PROJECT_WORK%\%ERROR_DOUBLE%"

echo.
echo === Fetching Positions ===
call getpositions.bat --filename %1 -s -r -w  %JSON_POS% -e %ERROR_DOUBLE%
if exist "%PROJECT_WORK%\%ERROR_DOUBLE%" (
    @echo -failed- errors found, e.g. duplicate IDs in given layout 
    pause
    move %PROJECT_WORK%\%ERROR_DOUBLE% %TARGET_DIR%
    move %PROJECT_WORK%\%JSON_TODRAW%  %TARGET_DIR%
    goto :eof
)
if not exist "%PROJECT_WORK%\%JSON_POS%" (
    @echo -failed- getpositions 
    pause
    goto :eof
)
echo.
echo === Creating Graph for Routing ===
call routing.bat --filename %JSON_POS% -w %JSON_TODRAW%
if not exist "%PROJECT_WORK%\%JSON_TODRAW%" (
    @echo -failed- routing
    pause
    goto :eof
)
echo.
echo === Writing Output Files === 
call draw_dxf.bat --filename %JSON_TODRAW% --new %DXF_RES% -x %EXCEL_RES% 
if not exist "%PROJECT_WORK%\%EXCEL_RES%" (
    @echo -failed- draw_dxf 
    pause
    goto :eof
)
echo.

move %PROJECT_WORK%\%FILENAME%_* %TARGET_DIR%
pause


:usage
@echo Usage: %0 ^<dxfinWorkOrdner.dxf^>
exit /B 1
goto :eof


