import Foundation


private let dateFormatter: DateFormatter = {
    let df = DateFormatter()
    df.dateStyle = .short
    df.timeStyle = .short
    return df
}()

private let justDateFormatter: DateFormatter = {
    let df = DateFormatter()
    df.dateStyle = .short
    df.timeStyle = .none
    return df
}()

private let timeFormatter: DateFormatter = {
    let df = DateFormatter()
    df.dateStyle = .none
    df.timeStyle = .short
    return df
}()

private let timeAndDataWithSecondsFormatter: DateFormatter = {
    let df = DateFormatter()
    df.dateStyle = .short
    df.timeStyle = .medium
    return df
}()

extension Date {

    var durationSinceNowText: String {
        let secondsAgo = -timeIntervalSinceNow
        guard secondsAgo > 2.5 else {
            return "Now"
        }
        guard secondsAgo > 60 else {
            let multiples = Int((secondsAgo / 5).rounded()) * 5
            return "\(multiples) seconds ago"
        }
        let minutesAgo = Int((secondsAgo / 60).rounded())
        guard minutesAgo > 1 else {
            return "\(minutesAgo) minute ago"
        }
        guard minutesAgo > 60 else {
            return "\(minutesAgo) minutes ago"
        }
        let hoursAgo = Int(Double(minutesAgo / 60).rounded())
        guard hoursAgo > 1 else {
            return "\(hoursAgo) hour ago"
        }
        guard hoursAgo > 24 else {
            return "\(hoursAgo) hours ago"
        }
        return dateFormatter.string(from: self)
    }

    var timeOrDateText: String {
        if Calendar.current.isDateInToday(self) {
            return timeFormatter.string(from: self)
        }
        return justDateFormatter.string(from: self)
    }

    var timeText: String {
        timeFormatter.string(from: self)
    }

    var timeAndDateText: String {
        dateFormatter.timeZone = .current
        return dateFormatter.string(from: self)
    }

    func timeAndDateText(in timeZone: TimeZone) -> String {
        dateFormatter.timeZone = timeZone
        return dateFormatter.string(from: self)
    }

    var timeAndDateWithSecondsText: String {
        timeAndDataWithSecondsFormatter.string(from: self)
    }
}
