### Persefone.jl - a model of agricultural landscapes and ecosystems in Europe.
###
### This file includes the functions for collecting and saving ecological output data.
###

"""
    initecologicaldata()

Create output files for each data group collected by the nature model.
"""
function initecologicaldata(model::SimulationModel)
    newdataoutput!(model, "populations", ["Date", "Species", "Abundance"],
                   savepopulationdata, @param(nature.popoutfreq), populationtrends)
    newdataoutput!(model, "individuals", ["Date","ID","X","Y","Species","Sex","Age"],
                   saveindividualdata, @param(nature.indoutfreq), visualisemap)
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::SimulationModel)
    pops = Dict{String,Int}(s=>0 for s = @param(nature.targetspecies))
    for a in model.animals
        isnothing(a) && continue
        pops[speciesof(a)] += 1
    end
    for m in model.migrants
        pops[speciesof(m.first)] += 1
    end
    data = []
    for p in keys(pops)
        push!(data, [model.date, p, pops[p]])
    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::SimulationModel)
    #XXX doesn't include migrants!
    data = []
    for a in model.animals
        isnothing(a) && continue
        push!(data, [model.date,a.id,a.pos[1],a.pos[2],speciesof(a),a.sex,a.age])
    end
    data
end