import Foundation
import Utilities

// Used to create and send song session context to analytics
public struct SongSessionContext: Codable {
    public let songSessionId: String
    public let previousSongSessionId: String?
    public let startTime: TimeInterval
    public let endTime: TimeInterval?
    public let playDuration: TimeInterval? // For the segment interrupted by the action
    public let totalPlayDuration: TimeInterval? // Accumulated for the song session
    public let isUserSongOwner: Bool
    public let volume: Float? // System audio volume at time of event
    public let previousHookId: String? // When opening OmniPlayer from Hooks
    public let previousHookSessionId: String? // When opening OmniPlayer from Hooks
    public let hookId: String? // When dismissing OmniPlayer after opening from a Hook
    public let contextType: String? // Context type (profile, library, playlist, etc.)
    public let contextId: String? // Context identifier (user handle, playlist ID, etc.)
    public let sourceUrl: String? // Source URL for deeplinks
    public let navigationIntent: String? // Navigation intent
    public let targetCommentId: String? // Target comment ID

    public init(
        songSessionId: String,
        previousSongSessionId: String? = nil,
        startTime: TimeInterval,
        endTime: TimeInterval? = nil,
        playDuration: TimeInterval? = nil,
        totalPlayDuration: TimeInterval? = nil,
        isUserSongOwner: Bool,
        volume: Float? = nil,
        previousHookId: String? = nil,
        previousHookSessionId: String? = nil,
        hookId: String? = nil,
        contextType: String? = nil,
        contextId: String? = nil,
        sourceUrl: String? = nil,
        navigationIntent: String? = nil,
        targetCommentId: String? = nil
    ) {
        self.songSessionId = songSessionId
        self.previousSongSessionId = previousSongSessionId
        self.startTime = startTime
        self.endTime = endTime
        self.playDuration = playDuration
        self.totalPlayDuration = totalPlayDuration
        self.isUserSongOwner = isUserSongOwner
        self.volume = volume
        self.previousHookId = previousHookId
        self.previousHookSessionId = previousHookSessionId
        self.hookId = hookId
        self.contextType = contextType
        self.contextId = contextId
        self.sourceUrl = sourceUrl
        self.navigationIntent = navigationIntent
        self.targetCommentId = targetCommentId
    }

    public func toJsonString() -> String {
        let encoder = JSONEncoder()
        if let data = try? encoder.encode(self),
           let string = String(data: data, encoding: .utf8)
        {
            return string
        }
        return "{}"
    }
}
