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

var KOUKOKU_W = 1024;
var KOUKOKU_H = 768;

function koukokuCjk(text) {
    if (text == null) return "";
    try { return String(TextUtil.getCjkParts(text)).trim(); }
    catch (e) { return String(text).trim(); }
}

function koukokuPlatformSize(list) {
    if (list == null) return 0;
    try { return list.size(); } catch (e) {}
    try { return list.length; } catch (e2) {}
    return 0;
}

function koukokuPlatformGet(list, index) {
    try { return list.get(index); } catch (e) {}
    return list[index];
}

function isOutOfService(train) {
    if (!train.isOnRoute()) return true;

    var idx = -1;
    var pls = null;

    // LED側と同じく thisRoute を優先。allPlatforms と index を混ぜない。
    try {
        idx = train.getThisRoutePlatformsNextIndex();
        pls = train.getThisRoutePlatforms();
    } catch (e) {
        return true;
    }

    var size = koukokuPlatformSize(pls);
    if (pls == null || size == 0 || idx < 0 || idx >= size) return true;

    var p = koukokuPlatformGet(pls, idx);
    if (p == null || p.route == null) return true;

    var typeJpn = koukokuCjk(p.route.lightRailRouteNumber);
    var destJpn = koukokuCjk(p.destinationName);

    return (typeJpn == "回送" || destJpn == "回送" || typeJpn == "試運転" || destJpn == "試運転");
}

function drawKoukokuImage(g, img) {
    if (img != null) {
        var iw = img.getWidth();
        var ih = img.getHeight();
        if (iw > 0 && ih > 0) {
            var scale = Math.max(KOUKOKU_W / iw, KOUKOKU_H / ih);
            var dw = Math.ceil(iw * scale);
            var dh = Math.ceil(ih * scale);
            var dx = Math.floor((KOUKOKU_W - dw) / 2);
            var dy = Math.floor((KOUKOKU_H - dh) / 2);
            g.drawImage(img, dx, dy, dw, dh, null);
            return;
        }
    }
    g.setColor(new Color(0.902, 0.902, 0.902));
    g.fillRect(0, 0, KOUKOKU_W, KOUKOKU_H);
}

function koukokuMain(g, state, train) {
    if (isOutOfService(train)) {
        drawKoukokuImage(g, state.koukoku_1);
        return;
    }

    var t = Date.now() % 70000;
    if (t < 10000) drawKoukokuImage(g, state.koukoku_1);
    else if (t < 20000) drawKoukokuImage(g, state.koukoku_2);
    else if (t < 30000) drawKoukokuImage(g, state.koukoku_3);
    else if (t < 40000) drawKoukokuImage(g, state.koukoku_4);
    else if (t < 50000) drawKoukokuImage(g, state.koukoku_5);
    else if (t < 60000) drawKoukokuImage(g, state.koukoku_6);
    else drawKoukokuImage(g, state.koukoku_7);
}
