//
//  Playable.swift
//  OasisPlayerPlugin
//
//  Created by Roman Karpievich on 7/20/20.
//

import Foundation
import ZappPlugins

class Playable {
    
    let sourceDictionary: NSDictionary
    
    let identifier: String?
    let clipID: String?
    let title: String?
    let isLive: Bool
    let domain: String?
    let tracking: NSDictionary?
    let extensions: NSDictionary?
    
    init(from dictionary: NSDictionary) {
        identifier = dictionary[FeedApiKeys.identifier.rawValue] as? String
        title = dictionary[FeedApiKeys.title.rawValue] as? String
        isLive = dictionary[FeedApiKeys.live.rawValue] as? Bool ?? false
        
        var extensions = dictionary[FeedApiKeys.extensions.rawValue] as? NSDictionary ?? [:]
        domain = extensions[FeedApiKeys.domain.rawValue] as? String
        
        if isLive == true {
            clipID = identifier
        } else if let streams = extensions["streams"] as? [String: [[String: Any]]],
                  let countryCode: String = streams.keys.first,
                  let stream = streams[countryCode]?.first,
                  let clipID = stream["id"] as? String  {
            self.clipID = clipID
            
            extensions = Playable.add(countryCode: countryCode,
                                      contentID: clipID,
                                      to: extensions)
        } else {
            clipID = identifier
        }
        
        tracking = extensions["tracking"] as? NSDictionary
        
        self.sourceDictionary = Playable.add(contentID: clipID ?? "", to: dictionary)
        self.extensions = extensions
    }
    
    private static func add(contentID: String,
                            to dictonary: NSDictionary) -> NSDictionary {
        let mutableDictionary = NSMutableDictionary(dictionary: dictonary)
        mutableDictionary["mediaUrl"] = "vas://\(contentID)"
        return mutableDictionary
    }
    
    private static func add(countryCode: String,
                            contentID: String,
                            to dictionary: NSDictionary) -> NSDictionary {
        let mutableDictionary = NSMutableDictionary(dictionary: dictionary)
        mutableDictionary["customData"] = ["country": countryCode,
                                           "clipId": contentID]
        return mutableDictionary
    }
}

enum SamplePlayables {
    case ranSports
    
    var sourceDictionary: NSDictionary {
        switch self {
        case .ranSports:
            return [
                "id": "6633731",
                "title": "Jalen Hurts übernimmt in Philly - Was bedeutet der Wechsel für die Eagles?",
                "live": false,
                "extensions": [:]
            ]
        }
    }
}

// https://developer.applicaster.com/Zapp-Pipes/5.-Feed-API.html

private enum FeedApiKeys: String {
    case identifier = "id"
    case extensions = "extensions"
    case title = "title"
    case live = "live"
    case domain = "domain"
}
