include(Resources.id("jsblock:scripts/pids_util.js"));

function create(ctx, state, pids) {
    print("Hello World ^^");
}

const LEDColors = {
    red: 0xFF0000,
    yellow: 0xFFFF00,
    green: 0x00FF00
};

function formatETA(arrivalTime, language) {
    const raw = arrivalTime; // e.g. "5 mins", "30 sec"

    if (raw == "") {
        if (language == "e") {
            return "Now";
        }
        if (language == "k") {
            return "지금";
        }
        if (language == "b") {
            return "Now|지금";
        }
    }

    const num = parseInt(raw); // gets X
    const isMinute = raw.includes("min");

    if (language === "e") {
        return num + (isMinute ? "min" : "sec");
    }

    if (language === "k") {
        return num + (isMinute ? "분" : "초");
    }

    if (language === "b") {
        return num + (isMinute ? "min|" + num + "분" : "sec|" + num + "초");
    }

    return raw; // fallback
}

function render(ctx, state, pids) {
    let language;
    let languageInput = pids.getCustomMessage(0);
    if (languageInput == "k") {
        language = "k";
    } else if (languageInput == "b") {
        language = "b";
    } else {
        language = "e";
    }


    Texture.create("background")
    .texture("jsblock:textures/led_bg.png")
    .size(186, 60)
    .draw(ctx);

    for (let i = 0; i < 3; i++) {
        let arrival = pids.arrivals().get(i);

        if (arrival != null) {
            Text.create("Arrival destination")
            .text(TextUtil.cycleString(arrival.destination()))
            .color(LEDColors.yellow)
            .pos(2, i * 20 + 5)
            .scale(1.5)
            .stretchXY()
            .size(90, 100)
            .draw(ctx);

            Text.create("Arrival time")
            .text(TextUtil.cycleString(formatETA(TextUtil.getNonCjkParts(PIDSUtil.getETAText(arrival.arrivalTime())), language)))
            .color(LEDColors.green)
            .pos(183, i * 20 + 5)
            .rightAlign()
            .scale(1.5)
            .stretchXY()
            .size(90, 100)  
            .draw(ctx);
        }
    }
}

function dispose(ctx, state, pids) {
    print("Goodbye World ^^;");
}