### Persefone - a socio-economic-ecological model of European agricultural landscapes.
###
### This file includes the functions for collecting and saving ecological output data.
###

const POPFILE = "populations.csv"
const INDFILE = "individuals.csv"

"""
    initecologicaldata()

Create output files for each data group collected by the nature model.
"""
function initecologicaldata(model::AgentBasedModel)
    newdataoutput!(model, POPFILE, "Date;Species;Abundance",
                   savepopulationdata, @param(nature.popoutfreq))
    newdataoutput!(model, INDFILE, "Date;ID;X;Y;Species;Sex;Age",
                   saveindividualdata, @param(nature.indoutfreq))
end

"""
    savepopulationdata(model)

Return a comma-separated set of lines (to be printed to `populations.csv`), giving
the current date and population size for each animal species. May be called never,
daily, monthly, yearly, or at the end of a simulation, depending on the parameter
`nature.popoutfreq`.
"""
function savepopulationdata(model::AgentBasedModel)
    pops = Dict{String,Int}(s=>0 for s = @param(nature.targetspecies))
    for a in allagents(model)
        (typeof(a) != Animal) && continue
        pops[a.traits["name"]] += 1
    end
    data = ""
    for p in keys(pops)
        data *= join([model.date, p, pops[p]], ";")*"\n"
    end
    data
end

"""
    saveindividualdata(model)

Return a comma-separated set of lines (to be printed to `individuals.csv`), listing
all properties of all animal individuals in the model. May be called never, daily,
monthly, yearly, or at the end of a simulation, depending on the parameter
`nature.indoutfreq`. WARNING: Produces very big files!
"""
function saveindividualdata(model::AgentBasedModel)
    data = ""
    for a in allagents(model)
        (typeof(a) != Animal) && continue
        entry = join([model.date,a.id,a.pos[1],a.pos[2],a.traits["name"],a.sex,a.age], ";")
        data *= entry*"\n"
    end
    data
end