local sensor  = peripheral.wrap("top")
local modem   = peripheral.wrap("back")
local op      = peripheral.wrap("bottom")
local channel = 65533

local whitelist = {
    "oddstr13",
    "lordgt55",
    "SafPlusPlus",
    "alekso56",
}

local coords = {
    {min = {x=2,    y=-2,    z=4},
     max = {x=3,    y=-1,    z=5},
     to  = {x=3.5,  y=62.51, z=-77.5}},
    {min = {x=4,    y=-3,    z=4},
     max = {x=5,    y=0,     z=5},
     to  = {x=-0.5, y=62.01, z=-77.5}},
}



if not modem.isOpen(channel) then
    modem.open(channel)
end

local function broadcastEvent(msg)
    modem.transmit(channel, 0, msg)
end



local function checkTP()
    for _,v in pairs(sensor.getPlayerNames()) do
        for _,p in pairs(whitelist) do
            if v == p then
                local player = sensor.getPlayerData(v)
                if player then
                    local x = player.position.x
                    local y = player.position.y
                    local z = player.position.z
                    --print(p, ', x=', x, ', y=', y, ', z=', z)
                    for _,c in pairs(coords) do
                        if c.min.x < x and c.max.x > x and
                           c.min.y < y and c.max.y > y and
                           c.min.z < z and c.max.z > z then
                            print("OK! teleporting.")
                            local oppe = op.getPlayerByName(p).asEntity()
                            oppe.setPosition(c.to.x, c.to.y, c.to.z)
                        end
                    end
                end
            end
        end
    end
end





local te = os.startTimer(1)
while true do
    local e, v1, v2, v3, v4 = os.pullEvent()
    print(e, ',', v1, ',', v2, ',', v3, ',', v4)
    if e == "chat_message" then
        if v2:sub(1,1) ~= "/" then
            broadcastEvent({type="chat", player=v1, message=v2})
        elseif v2:sub(1,4) == "/me " then
            broadcastEvent({type="action", player=v1, message=v2:sub(5,#v2)})
        end
    elseif e == "player_login" then
        broadcastEvent({type="login",   player=v1})
    elseif e == "player_logout" then
        broadcastEvent({type="logout",  player=v1})
    elseif e == "player_respawn" then
        broadcastEvent({type="respawn", player=v1})
    elseif e == "timer" then
        if v1 == te then
            te = os.startTimer(1)
            checkTP()
        end
    end
end

