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

// Внешние дисплеи (из 423.js)
let slotHeadDestCfg = {								// ЭМУ ОСНОВНОЙ ГОЛОВНОЙ (БЕЛЫЕ ОГНИ) ВАГОН
    version: 1,
    texSize: [1024, 128],
    slots: [
        {
            name: 'head-dest',
            texArea: [0, 0, 1024, 128],
            pos: [
                [
                    [-0.998944, 2.72939, 8.1436],		// Левый Верхний Угол XYZ
                    [-0.984691, 2.38098, 8.1436],	// Левый Нижний Угол XYZ
                    [0.98452, 2.38098, 8.1436],		// Правый Нижний Угол XYZ
                    [0.998928, 2.72939, 8.1436],				// Правый Верхний Угол XYZ
                ],
            ],
            offsets: [[0, 0, 0]],
        },
    ],
};

let slotHeadSideDestCfg = {								// ЭМУ ОСНОВНОЙ ГОЛОВНОЙ (БЕЛЫЕ ОГНИ) ВАГОН
    version: 1,
    texSize: [1024, 128],
    slots: [
        {
            name: 'head-right-dest',
            texArea: [0, 0, 1024, 128],
            pos: [
                [
                    [-1.43556, 2.04992, -3.59267],		// Левый Верхний Угол XYZ
                    [-1.43556, 1.79565, -3.59267],	// Левый Нижний Угол XYZ
                    [-1.43556, 1.79565, -2.51614],		// Правый Нижний Угол XYZ
                    [-1.43556, 2.04992, -2.51614],		// Правый Верхний Угол XYZ
                ],
            ],
            offsets: [[0, 0, 0]],
        },
        {
            name: 'head-left-dest',
            texArea: [0, 0, 1024, 128],
            pos: [
                [
                    [1.43512, 2.05035, 0.78823],		// Левый Верхний Угол XYZ
                    [1.43512, 1.79522, 0.78823],	// Левый Нижний Угол XYZ
                    [1.43512, 1.79522, -0.288302],		// Правый Нижний Угол XYZ
                    [1.43512, 2.05035, -0.288302],		// Правый Верхний Угол XYZ
                ],
            ],
            offsets: [[0, 0, 0]],
        },
    ],
};

let slotHeadSideDest2Cfg = {								// ЭМУ ОСНОВНОЙ ГОЛОВНОЙ (БЕЛЫЕ ОГНИ) ВАГОН
    version: 1,
    texSize: [1024, 128],
    slots: [
        {
            name: 'head-right-dest',
            texArea: [0, 0, 1024, 128],
            pos: [
                [
                    [-1.43523, 2.04991, -1.909],		// Левый Верхний Угол XYZ
                    [-1.43523, 1.79565, -1.909],	// Левый Нижний Угол XYZ
                    [-1.43523, 1.79565, -0.832464],		// Правый Нижний Угол XYZ
                    [-1.43523, 2.04991, -0.832464],		// Правый Верхний Угол XYZ
                ],
            ],
            offsets: [[0, 0, 0]],
        },
        {
            name: 'head-left-dest',
            texArea: [0, 0, 1024, 128],
            pos: [
                [
                    [1.43602, 2.05035, 2.47494],		// Левый Верхний Угол XYZ
                    [1.43602, 1.79522, 2.47494],	// Левый Нижний Угол XYZ
                    [1.43602, 1.79522, 1.3984],		// Правый Нижний Угол XYZ
                    [1.43602, 2.05035, 1.3984],		// Правый Верхний Угол XYZ
                ],
            ],
            offsets: [[0, 0, 0]],
        },
    ],
};

let slotHeadSideDest3Cfg = {								// ЭМУ ОСНОВНОЙ ГОЛОВНОЙ (БЕЛЫЕ ОГНИ) ВАГОН
    version: 1,
    texSize: [1024, 128],
    slots: [
        {
            name: 'head-right-dest',
            texArea: [0, 0, 1024, 128],
            pos: [
                [
                    [-1.43597, 2.04991, -0.27546],		// Левый Верхний Угол XYZ
                    [-1.43597, 1.79565, -0.27546],	// Левый Нижний Угол XYZ
                    [-1.43597, 1.79565, 0.801073],		// Правый Нижний Угол XYZ
                    [-1.43597, 2.04991, 0.801073],		// Правый Верхний Угол XYZ
                ],
            ],
            offsets: [[0, 0, 0]],
        },
        {
            name: 'head-left-dest',
            texArea: [0, 0, 1024, 128],
            pos: [
                [
                    [1.43617, 2.05035, 4.10848],		// Левый Верхний Угол XYZ
                    [1.43617, 1.79522, 4.10848],	// Левый Нижний Угол XYZ
                    [1.43617, 1.79522, 3.03194],		// Правый Нижний Угол XYZ
                    [1.43617, 2.05035, 3.03194],		// Правый Верхний Угол XYZ
                ],
            ],
            offsets: [[0, 0, 0]],
        },
    ],
};

let slotMidTailSideDestCfg = {								// ЭМУ ОСНОВНОЙ ГОЛОВНОЙ (БЕЛЫЕ ОГНИ) ВАГОН
    version: 1,
    texSize: [1024, 128],
    slots: [
       {
            name: 'mid-tail-right-dest',
            texArea: [0, 0, 1024, 128],
            pos: [
                [
                    [-1.43533, 2.05035, 1.41127],		// Левый Верхний Угол XYZ
                    [-1.43533, 1.79522, 1.41127],	// Левый Нижний Угол XYZ
                    [-1.43533, 1.79522, 2.48781],		// Правый Нижний Угол XYZ
                    [-1.43533, 2.05035, 2.48781],		// Правый Верхний Угол XYZ
                ],
            ],
            offsets: [[0, 0, 0]],
        },
        {
            name: 'mid-tail-left-dest',
            texArea: [0, 0, 1024, 128],
            pos: [
                [
                    [1.43619, 2.04992, 5.79218],		// Левый Верхний Угол XYZ
                    [1.43619, 1.79565, 5.79218],	// Левый Нижний Угол XYZ
                    [1.43619, 1.79565, 4.71565],		// Правый Нижний Угол XYZ
                    [1.43619, 2.04992, 4.71565],		// Правый Верхний Угол XYZ
                ],
            ],
            offsets: [[0, 0, 0]],
        },
        {
            name: 'mid-tail-dest',
            texArea: [0, 0, 1024, 128],
            pos: [
                [
                    [0.998942, 2.72939, -5.94348],		// Левый Верхний Угол XYZ
                    [0.984689, 2.38098, -5.94348],	// Левый Нижний Угол XYZ
                    [-0.984522, 2.38098, -5.94348],		// Правый Нижний Угол XYZ
                    [-0.99893, 2.72939, -5.94348],		// Правый Верхний Угол XYZ
                ],
            ],
            offsets: [[0, 0, 0]],
        },
    ],
};


let slotHeadRouteCfg = {							// ЭМУ МАРШРУТ ГОЛОВНОЙ (БЕЛЫЕ ОГНИ) ВАГОН
    version: 1,
    texSize: [256, 128],
    slots: [
        {
            name: 'head-route',
            texArea: [0, 0, 256, 128],
            pos: [
                [
                    [0, 0, 0],		// Левый Верхний Угол XYZ
                    [0, 0, 0],		// Левый Нижний Угол XYZ
                    [0, 0, 0],	    // Правый Нижний Угол XYZ
                    [0, 0, 0],	    // Правый Верхний Угол XYZ
                ],
            ],
            offsets: [[0, 0, 0]],
        },
    ],
};


let slotTailRouteCfg = {						    // ЭМУ МАРШРУТ ХВОСТОВОЙ (КРАСНЫЕ ОГНИ) ВАГОН
    version: 1,
    texSize: [256, 128],
    slots: [
        {
            name: 'tail-route',
            texArea: [0, 0, 256, 128],
            pos: [
                [
                    [0, 0, 0],     // Левый Верхний Угол XYZ
                    [0, 0, 0],     // Левый Нижний Угол XYZ
                    [0, 0, 0],     // Правый Нижний Угол XYZ
                    [0, 0, 0],     // Правый Верхний Угол XYZ
                ],
            ],
            offsets: [[0, 0, 0]],
        },
    ],
};

// Внутренние дисплеи (из 423_inside.js)
let slotHeadInsideDestCfg = {
    version: 1,
    texSize: [1024, 128],
    slots: [
        {
            name: 'head-another-inside-dest',
            texArea: [0, 0, 1024, 128],
            pos: [
                [
                     [-0.528613, 2.71228, -8.6444],
                    [-0.528613, 2.54395, -8.6444],
                    [0.528614, 2.54395, -8.6444],
                    [0.528614, 2.71228, -8.6444]
                ]
            ],
            offsets: [[0, 0, 0]]
        }
    ]
};

let slotMidInsideDestCfg = {
    version: 1,
    texSize: [1024, 128],
    slots: [
        {
            name: 'head-inside-dest',
            texArea: [0, 0, 1024, 128],
            pos: [
                [
                    [0.528614, 2.71229, 7.5489],
                    [0.528614, 2.54395, 7.5489],
                    [-0.528614, 2.54395, 7.5489],
                    [-0.528614, 2.71229, 7.5489]
                ]
            ],
            offsets: [[0, 0, 0]]
        },
        {
            name: 'head-another-inside-dest',
            texArea: [0, 0, 1024, 128],
            pos: [
                [
                    [-0.528613, 2.71228, -6.99025],
                    [-0.528613, 2.54395, -6.99025],
                    [0.528614, 2.54395, -6.99025],
                    [0.528614, 2.71228, -6.99025]
                ]
            ],
            offsets: [[0, 0, 0]]
        }
    ]
};

let slotMidInsideDest2Cfg = {
    version: 1,
    texSize: [1024, 128],
    slots: [
        {
            name: 'head-inside-dest',
            texArea: [0, 0, 1024, 128],
            pos: [
                [
                    [0.528614, 2.71229, 9.18297],
                    [0.528614, 2.54395, 9.18297],
                    [-0.528614, 2.54395, 9.18297],
                    [-0.528614, 2.71229, 9.18297]
                ]
            ],
            offsets: [[0, 0, 0]]
        },
        {
            name: 'head-another-inside-dest',
            texArea: [0, 0, 1024, 128],
            pos: [
                [
                    [-0.528613, 2.71228, -5.3565],
                    [-0.528613, 2.54395, -5.3565],
                    [0.528614, 2.54395, -5.3565],
                    [0.528614, 2.71228, -5.3565]
                ]
            ],
            offsets: [[0, 0, 0]]
        }
    ]
};

let slotMidTailInsideDestCfg = {
    version: 1,
    texSize: [1024, 128],
    slots: [
        {
            name: 'head-inside-dest',
            texArea: [0, 0, 1024, 128],
            pos: [
                [
                    [0.528616, 2.71228, 10.8437],
                    [0.528616, 2.54395, 10.8437],
                    [-0.52861, 2.54395, 10.8437],
                    [-0.52861, 2.71228, 10.8437]
                ]
            ],
            offsets: [[0, 0, 0]]
        }
    ]
};



// Создание помощников отображения для внешних дисплеев
let dhHeadBaseDest = new DisplayHelper(slotHeadDestCfg);
let dhHeadSideBaseDest = new DisplayHelper(slotHeadSideDestCfg);
let dhHeadSideBaseDest2 = new DisplayHelper(slotHeadSideDest2Cfg);
let dhHeadSideBaseDest3 = new DisplayHelper(slotHeadSideDest3Cfg);
let dhMidTailSideDest = new DisplayHelper(slotMidTailSideDestCfg);
let dhHeadBaseRoute = new DisplayHelper(slotHeadRouteCfg);

let dhTailBaseRoute = new DisplayHelper(slotTailRouteCfg);

// Создание помощников отображения для внутренних дисплеев
let dhHeadInsideBaseDest = new DisplayHelper(slotHeadInsideDestCfg);
let dhMidInsideBaseDest = new DisplayHelper(slotMidInsideDestCfg);
let dhMidInsideBaseDest2 = new DisplayHelper(slotMidInsideDest2Cfg);
let dhMidTailInsideDest = new DisplayHelper(slotMidTailInsideDestCfg);


// Общий шрифт
var EMUFont = Resources.readFont(Resources.idRelative('mtr:fronts/timessquare.ttf'));

function create(ctx, state, train) {
    // Инициализация внешних дисплеев
    state.pisRateLimit = new RateLimit(0.05);
    state.dhHeadDest = dhHeadBaseDest.create();
    state.dhHeadSideDest = dhHeadSideBaseDest.create();
    state.dhHeadSideDest2 = dhHeadSideBaseDest2.create();
    state.dhHeadSideDest3 = dhHeadSideBaseDest3.create();
    state.dhMidTailSideDest = dhMidTailSideDest.create();
    state.dhHeadRoute = dhHeadBaseRoute.create();
    state.dhTailRoute = dhTailBaseRoute.create();
    
    // Инициализация внутренних дисплеев
    state.pisRateLimitNextStation = new RateLimit(0.07);
    state.dhHeadInsideDest = dhHeadInsideBaseDest.create();
    state.dhMidInsideDest = dhMidInsideBaseDest.create();
    state.dhMidInsideDest2 = dhMidInsideBaseDest2.create();
    state.dhMidTailInsideDest = dhMidTailInsideDest.create();
   

    // Общие параметры
    state.routeIDmath = Math.floor(1 + (Math.random() * 59));
    state.routeID = state.routeIDmath;
    state.lastStationName = "";
    state.scrollOffset = 0;
    state.fullText = "";
    state.textWidth = 0;
    
    return state.routeID;
}

function dispose(ctx, state, train) {
    // Закрытие внешних дисплеев
    state.dhHeadDest.close();
    state.dhHeadSideDest.close();
    state.dhHeadSideDest2.close();
    state.dhHeadSideDest3.close();
    state.dhMidTailSideDest.close();
    state.dhHeadRoute.close();
    state.dhTailRoute.close();
    
    // Закрытие внутренних дисплеев
    state.dhHeadInsideDest.close();
    state.dhMidInsideDest.close();
    state.dhMidInsideDest2.close();
    state.dhMidTailInsideDest.close();
    
}

function render(ctx, state, train) {
    // Обработка внешних дисплеев
    if (state.pisRateLimit.shouldUpdate()) {
        let g;
        let EMUText = getDestinationStation(train);

        [
            { dh: state.dhHeadDest, graphicsName: 'head-dest' },
            { dh: state.dhHeadSideDest, graphicsName: 'head-right-dest' },
            { dh: state.dhHeadSideDest, graphicsName: 'head-left-dest' },
            { dh: state.dhHeadSideDest2, graphicsName: 'head-right-dest' },
            { dh: state.dhHeadSideDest2, graphicsName: 'head-left-dest' },
            { dh: state.dhHeadSideDest3, graphicsName: 'head-right-dest' },
            { dh: state.dhHeadSideDest3, graphicsName: 'head-left-dest' },
            { dh: state.dhMidTailSideDest, graphicsName: 'mid-tail-right-dest' },
            { dh: state.dhMidTailSideDest, graphicsName: 'mid-tail-left-dest' },
        ].forEach((element) => {
            let dh = element.dh;
            g = dh.graphicsFor(element.graphicsName);
            g.setColor(Color.BLACK);
            g.fillRect(0, 0, 1024, 128);
            g.setColor(Color.ORANGE);
            g.setFont(EMUFont.deriveFont(Font.PLAIN, 140));
            let fontMetrics = g.getFontMetrics();
            let textWidth = fontMetrics.stringWidth(EMUText);
            g.drawString(EMUText, (1024 - textWidth) / 2, 100);
            dh.upload();
        });
        
        [
            { dh: state.dhHeadRoute, graphicsName: 'head-route' },
            { dh: state.dhTailRoute, graphicsName: 'tail-route' },
        ].forEach((element) => {
            let dh = element.dh;
            g = dh.graphicsFor(element.graphicsName);
            g.setColor(Color.BLACK);
            g.fillRect(0, 0, 256, 128);
            g.setColor(Color.GREEN);
            g.setFont(EMUFont.deriveFont(Font.PLAIN, 110));
            g.drawString(state.routeID, 45, 115);
            dh.upload();
        });
    }

    // Отрисовка моделей внешних дисплеев
    ctx.drawCarModel(state.dhHeadDest.model, 0, null);
    ctx.drawCarModel(state.dhHeadSideDest.model, 0, null);
    ctx.drawCarModel(state.dhHeadSideDest2.model, 1, null);
    ctx.drawCarModel(state.dhHeadSideDest3.model, 2, null);
    ctx.drawCarModel(state.dhHeadRoute.model, 0, null);
    ctx.drawCarModel(state.dhMidTailSideDest.model, 3, null);
    ctx.drawCarModel(state.dhTailRoute.model, train.trainCars() - 1, null);

    // Обработка внутренних дисплеев
    let platformList = train.getThisRoutePlatforms();
    if (platformList.size() === 0) return;

    let currentPlatform = platformList[0];
    if (!currentPlatform || !currentPlatform.station) return;

    let currentStationName = currentPlatform.station.name;

    if (currentStationName !== state.lastStationName) {
        state.lastStationName = currentStationName;
        let nextStation = getNextStation(train);
        state.fullText = "Nächste station: " + nextStation + "          ";
        state.scrollOffset -= 0;
        
        let testG = state.dhHeadInsideDest.graphicsFor('head-another-inside-dest');
        testG.setFont(EMUFont.deriveFont(Font.PLAIN, 90));
        state.textWidth = testG.getFontMetrics().stringWidth(state.fullText);
    }

    if (state.pisRateLimitNextStation.shouldUpdate() && train.shouldRenderDetail()) {
        state.scrollOffset -= 20;
        if (state.scrollOffset < -state.textWidth) {
           state.scrollOffset += state.textWidth;
        }
        updateNextStationDisplay(state, train);
    }

    // Отрисовка моделей внутренних дисплеев
    ctx.drawCarModel(state.dhHeadInsideDest.model, 0, null);
    ctx.drawCarModel(state.dhMidInsideDest.model, 1, null);
    ctx.drawCarModel(state.dhMidInsideDest2.model, 2, null);
    ctx.drawCarModel(state.dhMidTailInsideDest.model, 3, null);

}

// Функции для внутренних дисплеев
function updateNextStationDisplay(state, train) {
    ['head-inside-dest', 'head-another-inside-dest'].forEach(slotName => {
        updateDisplaySlot(state.dhMidInsideDest, slotName, state);
        updateDisplaySlot(state.dhMidInsideDest2, slotName, state);
      
    });

    ['head-inside-dest'].forEach(slotName => {
        updateDisplaySlot(state.dhMidTailInsideDest, slotName, state);

    });

    ['head-another-inside-dest'].forEach(slotName => {
        updateDisplaySlot(state.dhHeadInsideDest, slotName, state);
    });
}

function updateDisplaySlot(dh, slotName, state) {
    let g = dh.graphicsFor(slotName);
    g.setComposite(AlphaComposite.Clear);
    g.fillRect(0, 0, 1024, 128);
    g.setComposite(AlphaComposite.SrcOver);
    g.setColor(Color.ORANGE);
    g.setFont(EMUFont.deriveFont(Font.PLAIN, 90));
    
    g.drawString(state.fullText, state.scrollOffset, 100);
    
    if (state.scrollOffset + state.textWidth < 1024) {
        g.drawString(state.fullText, state.scrollOffset + state.textWidth, 100);
    }
    
    dh.upload();
}

function getNextStation(train) {
    let stationList = train.getThisRoutePlatforms();
    let nextstationindex = train.getThisRoutePlatformsNextIndex();
    return stationList[nextstationindex].station.name;
}

function updateDisplays(state, text) {
    state.scrollText = text + "    ";
    state.scrollPosition = 0;
    updateDestinationDisplays(state, text);
    updateRouteDisplays(state);
}

// Общая функция для получения конечной станции
function getDestinationStation(train) {
    let stationList = train.getThisRoutePlatforms();
    let lastPlatform = stationList[stationList.size() - 1];
    return lastPlatform === undefined ? 'NICHT EINSTEIGEN' : lastPlatform.destinationName.split('\\|')[0];
}