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

include("ikisaki.js");
include("ikisaki_head.js");
include("led.js");

let g;

function create(ctx, state, train) {
    state.dh = dhBase.create();

    state.rate = new RateLimit(0.5);      // 外側（行先など）
    state.ledRate = new RateLimit(0.05);  // 車内LED

    state.lastDoor = false;
    state.isScrolling = false;
    state.scrollStartTime = 0;

    // 128x32（ikisaki用）
    ensureSmallCanvas(state);
}

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

function render(ctx, state, train) {
    if (!train.shouldRender()) return;

    let drew = false;

    // ===== 外側 =====
    if (state.rate.shouldUpdate()) {
        g = state.dh.graphicsFor("out_left");
        ikisakiMain(g, state, train);

        g = state.dh.graphicsFor("out_right");
        ikisakiMain(g, state, train);

        g = state.dh.graphicsFor("out_front");
        ikisakiHead(g, state, train);

        g = state.dh.graphicsFor("out_back");
        ikisakiHead(g, state, train);

        drew = true;
    }

    // ===== 車内LED =====
    if (state.ledRate.shouldUpdate()) {
        g = state.dh.graphicsFor("led_left");
        ledmain(g, state, train);

        g = state.dh.graphicsFor("led_right");
        ledmain(g, state, train);

        drew = true;
    }

    // ★描いた時だけ upload
    if (drew) state.dh.upload();

    for (let i = 0; i < train.trainCars(); i++) {
        ctx.drawCarModel(state.dh.model, i, null);
    }
}

