local super = require "DateFormatter"

AutoDateFormatter = super:new()

local function _isdate(date)
    return (date and type(date) == 'userdata' and date.year) and true
end

local function _hasmultiple(table)
    local count = 0
    for _ in pairs(table) do
        count = count + 1
    end
    return count > 1
end

function AutoDateFormatter:evaluate(sequence)
    local years, months, days, hours, minutes, seconds = {}, {}, {}, {}, {}, {}
    sequence:each(function(value)
        if _isdate(value) then
            years[value:year()] = true
            months[value:month()] = true
            days[value:day()] = true
            hours[value:hour()] = true
            minutes[value:minute()] = true
            seconds[math.floor(value:second())] = true
        end
    end)
    years = _hasmultiple(years)
    months = _hasmultiple(months)
    days = _hasmultiple(days)
    hours = _hasmultiple(hours)
    minutes = _hasmultiple(minutes)
    seconds = _hasmultiple(seconds)
    
    local dateTemplate, timeTemplate, template
    if years and not (months or days or hours or minutes or seconds) then
        dateTemplate = 'year'
    elseif months and not (days or hours or minutes or seconds) then
        dateTemplate = 'year-month-long'
    elseif days and not (hours or minutes or seconds) then
        if years then
            dateTemplate = 'year-month-day-long'
        else
            dateTemplate = 'month-day-long'
        end
    elseif days then
        if years then
            dateTemplate = 'year-month-day-abbreviated'
        else
            dateTemplate = 'month-day-abbreviated'
        end
    end
    if seconds then
        timeTemplate = 'hour-12-minute-second'
    elseif minutes then
        timeTemplate = 'hour-12-minute'
    elseif hours then
        if days then
            timeTemplate = 'hour-12'
        else
            timeTemplate = 'hour-12-minute'
        end
    end
    if dateTemplate and timeTemplate then
        template = dateTemplate .. ' ' .. timeTemplate
    else
        template = dateTemplate or timeTemplate or 'year-month-day-long'
    end
    
    return DateFormatter:new(template):evaluate(sequence)
end

return AutoDateFormatter
