import APIClient
import ComponentLibrary
import Foundation

extension CommentsThread {
    /// Finds the @mention currently being typed at the end of text
    func extractCurrentMention(from text: String) -> String? {
        InteractiveTextFormatter.extractCurrentMention(from: text)
    }

    /// Replaces @mention with user's display name and updates mentions list
    func replacePendingMention(
        from text: String,
        for user: SimpleProfile,
        mentions: inout [CommentUserMention]
    ) -> String {
        InteractiveTextFormatter.replacePendingMention(
            from: text,
            for: user,
            mentions: &mentions
        ) { start, end, handle, displayName in
            CommentUserMention(start: start, end: end, handle: handle, displayName: displayName)
        }
    }

    func isValidMention(_ mention: CommentUserMention, in text: String) -> Bool {
        InteractiveTextFormatter.isValidMention(mention, in: text)
    }
}

extension CommentsThread {
    /// The user might want to send the comment for a specific part in the track,
    /// but by the time they finish typing, that part of the track might have past.
    /// Lock the track timestamp when a specific condition is met.
    func lockTrackTimeIfNeeded(state: inout State, when shouldLock: Bool) {
        if shouldLock, state.lockedTrackTime == nil {
            state.lockedTrackTime = state.elapsedTrackTime
        }
    }

    func unlockTrackTimeIfNeeded(state: inout State, when shouldUnlock: Bool) {
        if shouldUnlock, state.lockedTrackTime != nil {
            state.lockedTrackTime = nil
        }
    }
}
