const addS = (num, unit) =>
    num === 1 ?
        unit :
        unit + 's';

export const toTimeString = (date) => {
    const now = Date.now();
    const diff = date - now;
    if (Number.isNaN(diff)) {
        return '';
    }
    const ms = Math.abs(date - now);
    const time = new Date(ms);
    const days = ms / 1000 / 60 / 60 / 24 | 0;
    const hours = time.getUTCHours();
    const minutes = time.getUTCMinutes();
    const seconds = time.getUTCSeconds();
    const parts = [];
    (days > 0) && parts.push(days, addS(days, 'day'));
    (hours > 0) && parts.push(hours, addS(hours, 'hour'));
    (minutes > 0) && parts.push(minutes, addS(minutes, 'minute'));
    (seconds >= 0) && parts.push(seconds, addS(seconds, 'second'));

    if (date > now) {
        parts.unshift('in');
    } else {
        parts.push('ago');
    }

    if (typeof date === 'number') {
        date = new Date(date);
    }
    parts.push('(', date.toISOString(), ')');

    return parts.join(' ');
};
