importPackage(java.awt);
importPackage(java.awt.geom);
include(Resources.id('mtrsteamloco:scripts/display_helper.js'));

let slotCfg = {
    version: 1,
    texSize: [1024, 128],
    slots: [
        {
            name: 'head',
            texArea: [0, 0, 1024, 128],
            pos: [
                [
                    [-0.5, 0.92, 10.16],
                    [-0.5, 0.8, 10.16],
                    [0.52, 0.8, 10.16],
                    [0.52, 0.92, 10.16],
                ],
            ],
            offsets: [[0, 0, 0]],
        },
    ],
};

let dhBase = new DisplayHelper(slotCfg);

function create(ctx, state, train) {
	state.dh = dhBase.create();
	state.rate = new RateLimit(0.08);

	drawDispl(state, train)
}

function dispose(ctx, state, train) {
	if (state.dh != null) {
		state.dh.close();
	}
}

var EMUFont = Resources.readFont(
    Resources.idRelative('mtr:minsk/fonts/arial.ttf')
);

function render(ctx, state, train) {
	updateDispl(ctx, state, train);
}

function updateDispl(ctx, state, train){
	if (state.rate.shouldUpdate()){
		updateEmuStrings(state, train);
		drawDispl(state, train);
	}
}

function updateEmuStrings(state, train) {
  if (train.getThisRoutePlatforms().size() != 0) {
    state.isOnRoute = true;
  } else {
    state.isOnRoute = false
  }
}

function drawDispl(state, train){
        let EMUText = getDestinationStation(train);

	//ЭМУ головной вагон
	let g = state.dh.graphics();
            g.setColor(Color.BLACK);
            g.fillRect(0, 0, 1024, 128);
            g.setColor(Color.ORANGE);
            g.setFont(EMUFont.deriveFont(Font.PLAIN, 110));
            let fontMetrics = g.getFontMetrics();
            let routeWidth = 0;
            let textWidth = fontMetrics.stringWidth(EMUText);
            g.drawString(
                EMUText,
                routeWidth + (1024 - routeWidth - textWidth) / 2,
                100
            );
            state.dh.upload();
}

function getDestinationStation(train) {
    let stationList = train.getThisRoutePlatforms();
    let lastPlatform = stationList[stationList.size() - 1];
    if (lastPlatform === undefined) return 'нет посадки';
    return lastPlatform.destinationName.split('\\|')[0].toUpperCase();
}
