local S = core.get_translator(core.get_current_modname());
local F = core.formspec_escape;

local storage = core.get_mod_storage();

function warp_portal.teleport_formspec(pos, user, status)
    local btn_name = "Turn ON";
    local btn_id = "portal_turn_on";

    if (status == true) then btn_name = "Turn OFF"; end;
    if (status == true) then btn_id = "portal_turn_off"; end;
    
    local list = {};
    for i, key in pairs(warp_portal.storage_get_keys(storage)) do
        local value = storage:get_string(key);
        if (value ~= "off") and (status == true) then
            table.insert(
                list, 
                "button[0,"..tostring(0.6*(i-1))..";4.5,0.5;"..
                "warp_to_"..value..";"..
                key.."]"
            );
        else
            table.insert(
                list, "hypertext[0,"..tostring(0.6*(i-1))..";4.5,0.5;"..
                "btn_off;"..key.."]"
            );
        end;
    end;
    
    local meta = core.get_meta(pos);
    local portal_name = meta:get_string("infotext");
    
    core.show_formspec(user:get_player_name(),
        "warp_portal:teleport_"..pos.x.."_"..pos.y.."_"..pos.z,
        table.concat({
            "formspec_version[4]", "size[5.475,7.475]",

            "label[0.375,0.375;" .. F("Warp Portal: ") .. portal_name .. "]",
            
            "scroll_container[0.375,0.875;5,5;scroll;vertical;0.1]",
            table.concat(list),
            "scroll_container_end[]",
            "scrollbaroptions[max="..tostring(2.9*#warp_portal.storage_get_keys(storage)).."]",
            "scrollbar[5,0.875;0.32,5;vertical;scroll;0]",
            
            "button[0.375,6.3;4.6,0.8;"..btn_id..";"..btn_name.."]",
        })
    );
end;

function warp_portal.set_name_formspec(pos, user, name, warning)
    warning, name = warning or "", name or "";
    
    core.show_formspec(user:get_player_name(),
        "warp_portal:set_name_"..pos.x.."_"..pos.y.."_"..pos.z,
        table.concat({
            "formspec_version[4]", "size[5.475,3.475]",

            "label[0.375,0.375;" .. F("Warp Portal: Set Name") .. "]",
            
            "field[0.375,1.05;4.6,0.8;portal_name;Portal Name;"..name.."]",
            "label[0.375,2.1;" .. warning .. "]",
            
            "button[0.375,2.3;4.6,0.8;portal_name_done;Done]",
        })
    );
end;