PreciseReceivedText = {}

PreciseReceivedText.name = "PreciseReceivedText"

local function _GetReceivedText (original_function)
    return function (self)
        local function divmod (a, b)
            return math.floor(a/b), a%b
        end

        if not self.receivedText then
            local t = original_function(self)
            local secs = self.secsSinceReceived

            local weeks, secs = divmod(secs, 7*24*60*60)
            if weeks == 0 then weeks = nil end
            local days, secs = divmod(secs, 24*60*60)
            if days == 0 then days = nil end
            local hours, secs = divmod(secs, 60*60)
            if hours == 0 then hours = nil end
            local minutes, secs = divmod(secs, 60)
            if minutes == 0 then minutes = nil end

            local n_t = ""

            if weeks then
                n_t = n_t .. weeks .. "wk, "
            end
            if days then
                n_t = n_t .. days .. "d, "
            end
            if hours then
                n_t = n_t .. hours .. "h, "
            end
            if minutes then
                n_t = n_t .. minutes .. "m, "
            end
            n_t = n_t .. secs .. "s ago."

            self.receivedText = n_t
            return n_t
        else
            return original_function(self)
        end
    end
end

function PreciseReceivedText:Initialize()
    local zo = ZO_MailInboxShared_PopulateMailData
    ZO_PreHook("ZO_MailInboxShared_PopulateMailData", function (dataTable, mailId)
        zo(dataTable, mailId)
        dataTable.GetReceivedText = _GetReceivedText(dataTable.GetReceivedText)
        return true
    end)
end

function PreciseReceivedText.OnAddOnLoaded(event, addonName)
    if addonName == PreciseReceivedText.name then
        PreciseReceivedText:Initialize()
    end
end

EVENT_MANAGER:RegisterForEvent(PreciseReceivedText.name, EVENT_ADD_ON_LOADED, PreciseReceivedText.OnAddOnLoaded)