### Persephone - a socio-economic-ecological model of European agricultural landscapes.
###
### This file manages the landscape maps that underlie the model.
###

## The land cover classes encoded in the Mundialis Sentinel data.
## Do not change the order of this enum, or initlandscape() will break!
@enum LandCover nodata forest grass water builtup soil agriculture

"""
    Pixel

A pixel is a simple data structure to combine land use and ownership information
in a single object. The model landscape consists of a matrix of pixels.
(Note: further landscape information may be added here in future.)
"""
struct Pixel
    landcover::LandCover
    fieldid::Union{Missing, UInt32}
    events::Vector{Symbol} #TODO implement the rest of the events system
    #FIXME actually this is stupid - I don't want a field ID, I want a field object
end

"""
    initlandscape()

Initialise the model landscape based on the map files specified in the
configuration. Returns a matrix of pixels.
"""
function initlandscape()
    @debug "Initialising landscape"
    landcover = GeoArrays.read(param("core.landcovermap"))
    farmfields = GeoArrays.read(param("core.farmfieldsmap"))
    (size(landcover) != size(farmfields)) && Base.error("Input map sizes don't match.")
    width, height = size(landcover)[1:2]
    landscape = Matrix{Pixel}(undef, width, height)
    for x in 1:width
        for y in 1:height
            # convert the numeric landcover value to LandCover, then create the Pixel object
            lc = landcover[x,y][1]
            (ismissing(lc)) && (lc = 0)
            lcv = LandCover(Int(lc/10))
            landscape[x,y] = Pixel(lcv, farmfields[x,y][1])
        end
    end
    return landscape
end


"""
    landcover(model, position)

Return the land cover class at this position (utility wrapper).
"""
function landcover(model::AgentBasedModel, pos::Tuple{Int64,Int64})
    model.landscape[pos...].landcover
end

"""
    fieldid(model, position)

Return the UID of the field at this position (utility wrapper).
"""
function fieldid(model::AgentBasedModel, pos::Tuple{Int64,Int64})
    model.landscape[pos...].fieldid
end