local sit = require 'room.sit'
local plants = require 'objects.plants'

local staff_data = serialize.define({
    {"sit", "bool"}
})

local common = require 'room.common'
encode_tooltip = common.encode_tooltip_def
decode_tooltip = common.decode_tooltip_def

function update(room)
    local objects = room.objects
    local num_chairs = sit.seat_capacity(objects)
    room.capacity = num_chairs
end

function save(room)
    local visitors = room.visitors
    local objects = room.objects

    local v_data = {}
    for _, e in ipairs(visitors) do
        v_data[e.id] = {
            sit = sit.save_sitter(room, e),
        }
    end

    return {
        plants = plants.save_plants(room),
        seats = sit.save_seats(room),
        visitors = v_data,
    }
end

function load(room, data)
    plants.load_plants(room, data.plants)
    sit.load_seats(room, data.seats)
    local visitors = room.visitors
    local objects = room.objects

    for _, e in ipairs(visitors) do
        local d = data.visitors[e.id]
        sit.load_sitter(room, e, d.sit)
    end

end

function force_entity_release(room, e)
    sit.release_seat(e)
end

function server(room)
    local visitors = room.visitors
    local objects = room.objects

    plants.tick_plants(room)

    for _, e in ipairs(room.owned) do
        e:release()
    end

    for _, e in ipairs(visitors) do
        local data = {}
        if e.should_release then
            sit.release_seat(e)
            if sit.try_stand(e, data) then
                e:release()
            else
                e.state = staff_data.encode(data)
            end
        else
            if not e.is_walking then
                local state = sit.try_find_and_sit(e, data, objects)
                if state == sit.SITTING then
                    e.state = staff_data.encode(data)
                    e:change_stat("fatigue", 0.004 / 20.0)
                    e:change_stat("happiness", 0.004 / 20.0)
                end
            end
        end
    end
end

function client(room, entities)
    for _, e in ipairs(entities) do
        if e.state ~= nil then
            local data = staff_data.decode(e.state)
            sit.client_sit_tick(e, data)
        end
    end
    plants.tick_plants_client(room)
end

function on_exec(room, method, data)
    plants.on_exec(room, method, data)
end