importPackage(java.awt);
importPackage(java.awt.geom);

include("draw_head_display.js");
include("mtr_util.js");

var meetNTEVersionRequirement = Resources.getNTEVersionInt() >= 402;
var isMTR4 = Resources.getMTRVersion().includes("4.0");

function create(ctx, state, train) {
    state.terminalScreen = null;
    state.lastTerminalText = "";
}

function dispose(ctx, state, train) {
    if (state.terminalScreen) {
        state.terminalScreen.close();
    }
}

function render(ctx, state, train) {
    if (!meetNTEVersionRequirement || isMTR4) {
        return;
    }

    let trainStatus = getTrainStatus(train);
    
    let platformInfo;
    switch (trainStatus) {
        case STATUS_NO_ROUTE:
            platformInfo = null;
            break;
        case STATUS_RETURNING_TO_DEPOT:
            platformInfo = train.getAllPlatforms().get(train.getAllPlatforms().size() - 1);
            break;
        case STATUS_WAITING_FOR_DEPARTURE:
            platformInfo = train.getAllPlatforms().get(0);
            break;
        case STATUS_CHANGING_ROUTE:
            platformInfo = train.getAllPlatforms().get(train.getAllPlatformsNextIndex());
            break;
        default:
            platformInfo = train.getThisRoutePlatforms().get(train.getThisRoutePlatformsNextIndex());
            break;
    }

    const routeInfo = getRouteInfo(train, trainStatus, platformInfo);
    
    if (routeInfo == null) {
        return;
    }

    if (!checkJsonProperty(state, "routeInfo", routeInfo)) {
        state.routeInfo = routeInfo;
        state.lastTerminalText = "";
    }

    let terminalText = routeInfo.destination;
    if (state.lastTerminalText != terminalText) {
        state.lastTerminalText = terminalText;
        
        if (state.terminalScreen) {
            state.terminalScreen.close();
        }
        
        state.terminalScreen = createTerminalScreen(1, 1, terminalText);
    }
    
    if (state.terminalScreen) {
        let terminalMatricesFirst = new Matrices();
        terminalMatricesFirst.translate(0, 2.23, 8.83);
        ctx.drawCarModel(state.terminalScreen.dynamicModelHolder, 0, terminalMatricesFirst);
        
        let lastCarIndex = train.trainCars() - 1;
        if (lastCarIndex > 0) {
            let terminalMatricesLast = new Matrices();
            terminalMatricesLast.translate(0, 2.23, -8.83);
            terminalMatricesLast.rotateY(Math.PI);
            ctx.drawCarModel(state.terminalScreen.dynamicModelHolder, lastCarIndex, terminalMatricesLast);
        }
    }
}
