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

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

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

    const num = parseInt(raw); // gets X

    if (!num) {
        return [localization[language].now, 0xFFFF00];
    }

    const isMinute = raw.includes("min");

    if (language === "e") {
        return [num + (isMinute ? "m" : "s"), 0xFFFFFF];
    }

    if (language === "k") {
        return [num + (isMinute ? "분" : "초"), 0xFFFFFF];
    }

    if (language === "b") {
        return [num + (isMinute ? "m|" + num + "분" : "s|" + num + "초"), 0xFFFFFF];
    }

    return [raw, 0xFFFFFF]; // fallback
}

let localization = {
    "e": {
        now: "Now"
    },
    "k": {
        now: "지금"
    },
    "b": {
        now: "Now|지금"
    }
};

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/bus_pids_new.png")
    .size(186, 60)
    .draw(ctx);

    let arrivingBuses = [];

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

        if (arrival == null) {
            break;
        }

        let arrivalTime = formatETA(TextUtil.getNonCjkParts(PIDSUtil.getETAText(arrival.arrivalTime())), language);
        arrivingBuses.push([arrival.routeNumber(), arrivalTime, arrival.routeColor()]);
    }

    for (let i = 0; i < 3; i++) {
        if (arrivingBuses[i] != null) {
            Text.create("Arrival route")
            .text(arrivingBuses[i][0])
            .color(arrivingBuses[i][2])
            .pos(i * 61.5 + 5, 7.5)
            .scale(2.2)
            .bold()
            .draw(ctx);

            Text.create("Arrival time")
            .text(TextUtil.cycleString(arrivingBuses[i][1][0]))
            .color(arrivingBuses[i][1][1])
            .pos(i * 61.5 + 5, 26)
            .scale(1.2)
            .draw(ctx);
        }
    }

    for (let i = 0; i < 6; i++) {
        if (arrivingBuses[i + 3] != null) {
            Text.create("Arrival route")
            .text(arrivingBuses[i + 3][0])
            .color(arrivingBuses[i + 3][2])
            .pos(i * 31 + 15.5, 40.25)
            .centerAlign()
            .scale(1.5)
            .draw(ctx);

            Text.create("Arrival time")
            .text(TextUtil.cycleString(arrivingBuses[i + 3][1][0]))
            .color(arrivingBuses[i + 3][1][1])
            .pos(i * 31 + 15.5, 50.75)
            .centerAlign()
            .scale(1.2)
            .draw(ctx);
        }
    }
}

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