module SusanHelperBigFungus

using ..Ahorn, Maple

@mapdef Entity "SusanHelper/BigFungus" BigFungus(x::Integer, y::Integer, width::Integer=8, hitSpd::Number=200.0, type::String="Green")

types = ["Green", "Red", "Orange", "Blue", "Cyan"]

const placements = Ahorn.PlacementDict(
    "Big Fungus (Susan Helper)" => Ahorn.EntityPlacement(
        BigFungus,
        "rectangle",
    )
)

quads = Tuple{Integer, Integer, Integer, Integer}[
    (0, 0, 8, 7) (8, 0, 8, 7) (16, 0, 8, 7);
    (0, 8, 8, 5) (8, 8, 8, 5) (16, 8, 8, 5)
]

Ahorn.minimumSize(entity::BigFungus) = 8, 0
Ahorn.resizable(entity::BigFungus) = true, false

function Ahorn.selection(entity::BigFungus)
    x, y = Ahorn.position(entity)
    width = Int(get(entity.data, "width", 8))

    return Ahorn.Rectangle(x, y, width, 8)
end

Ahorn.editingOptions(entity::BigFungus) = Dict{String, Any}(
    "type" => types
)

function Ahorn.render(ctx::Ahorn.Cairo.CairoContext, entity::BigFungus, room::Maple.Room)

    x = Int(get(entity.data, "x", 0))
    y = Int(get(entity.data, "y", 0))

    width = Int(get(entity.data, "width", 8))

    startX = div(x, 8) + 1
    stopX = startX + div(width, 8) - 1
    startY = div(y, 8) + 1

    len = stopX - startX
    for i in 0:len
        connected = false
        qx = 2
        if i == 0
            connected = get(room.fgTiles.data, (startY, startX - 1), false) != '0'
            qx = 1

        elseif i == len
            connected = get(room.fgTiles.data, (startY, stopX + 1), false) != '0'
            qx = 3
        end

        quad = quads[2 - connected, qx]
        Ahorn.drawImage(ctx, "objects/bigFungus/gmush", 8 * i, 0, quad...)
    end
end

end