//
//  ViewController.swift
//  ModifiersDemo
//
//

import AVFoundation
import CastlabsApple
import PRESTOplay
import UIKit

let CONTENT_URL = "https://demo.cf.castlabs.com/media/fps/prog_index.m3u8"

let CERTIFICATE_URL = "DRMTODAY_STAGING_CERTIFICATE_URL"
let LICENSING_URL = "DRMTODAY_STAGING_LICENSING_URL"

let MERCHANT = "DRMTODAY_MERCHANT"
let USER_ID = "DRMTODAY_USER_ID"
let SESSION_ID = "DRMTODAY_SESSION_ID"

class ViewController: UIViewController {
    // create player instance
    var player = PRESTOplaySDK.shared.player()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        // optional: ignore silent switch
        try? AVAudioSession.sharedInstance().setCategory(.playback)
        guard let contentURL = URL(string: CONTENT_URL) else { return }

        let config = PlayerConfiguration(with: contentURL)
        config.drmType = .custom
        config.drmSystem = .fairplay
        config.drmConfiguration = DrmConfiguration()
        config.drmConfiguration?.certificateUrl = URL(string: CERTIFICATE_URL)
        config.drmConfiguration?.licensingUrl = URL(string: LICENSING_URL)

        player.requestModifiers = [RequestModifier()]
        player.responseModifiers = [ResponseModifier()]

        player.load(config: config)
        player.onState = { [weak self] previous, state in
            guard let self else { return }
            if let error = player.error {
                print("Error \(error)")
            }
        }

        player.attach(to: view.layer)
        player.open(autoplay: true)
    }

    override func viewWillTransition(
        to size: CGSize,
        with coordinator: UIViewControllerTransitionCoordinator
    ) {
        player.update(size: size)
    }
}

// MARK: - Request and Response Modifiers

// MARK: - DRMToday

struct RequestModifier: RequestModifierProtocol {
    func modify(_ request: Request,
                completionHandler: @escaping (Request?) -> Void) {
        if request.type == .asset {
//            --- Note: rewrite assetId used as 'contentIdentifier'
//            request.url = URL(string: "assetId")!
            completionHandler(request)
            return
        }

        if request.type == .provision {
            completionHandler(request)
            return
        }

        if request.type == .license {
            let queryKeyValueString = CharacterSet(charactersIn: ":?=&+").inverted
            let encodedSpcMessage = request.data?
                .base64EncodedString()
                .addingPercentEncoding(
                    withAllowedCharacters: queryKeyValueString
                ) ?? ""

            request.data = String(format: "spc=%@", encodedSpcMessage).data(using: .utf8)
            var dict = [String: String]()
            dict["merchant"] = MERCHANT
            dict["userId"] = USER_ID
            dict["sessionId"] = SESSION_ID

            do {
                let customData = try JSONSerialization.data(withJSONObject: dict, options: [])
                request.headers["x-dt-custom-data"] = customData.base64EncodedString()
            } catch { }

            completionHandler(request)
            return
        }
    }
}

struct ResponseModifier: ResponseModifierProtocol {
    func modify(_ response: Response,
                completionHandler: @escaping (Response?) -> Void) {
//      --- Note: unwrap certificate and/or license response
        print("\n\n---> \(String(describing: response.type))\n\n\(String(describing: response.url))\n\n\(response.headers)\n")

        if response.type == .license,
           let base64encoded = response.data {
            response.data = Data(base64Encoded: base64encoded)
        }

//        to fail the response
//        response.data = nil

        completionHandler(response)
    }
}
