//
//  ViewController.swift
//  CastlabsDASHWidevineDemo
//
//

import PRESTOplay
import CastlabsVTWithWidevine
import AVFoundation
import UIKit

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)

        /// Clear:
        /// https://demo.cf.castlabs.com/media/TOS/abr/Manifest_clean_sizes.mpd?v=10
        ///
        /// Widevine:
        /// https://demo.cf.castlabs.com/media/bbb_abr/Manifest.mpd
        ///
        guard let contentURL =
            URL(
                string: "https://demo.cf.castlabs.com/media/TOS/abr/Manifest_clean_sizes.mpd?v=10")
        else { return }

        let config = PlayerConfiguration(with: contentURL)

        /// ABR configuration
        /*
        config.abrConfiguration = AbrConfiguration()
        config.abrConfiguration?.minDurationForQualityIncreaseMs = 3 * 1000
        config.abrConfiguration?.maxInitialBitrate = 500_000
        */

        /// Buffer configuration
        /*
        player.minPrebufferTime = 6.0
        player.maxPrebufferTime = 60.0
        player.minRebufferTime = 12.0
        */

        /// Live configuration
        /*
        player.liveEdgeDelay = 6.0
        player.chaseLiveEdge = .speedupPlayback
        player.chaseLiveEdgeCatchupThreshold = 3.0
        player.chaseLiveEdgeCutoffThreshold = 2.0
        player.chaseLiveEdgeHLSSegmentDuration = 10.0
        player.chaseLiveEdgeSpeedupRatio = 1.2
        */

        /// DRM Widevine configuration
        ///
        /// Please check README.md attached to the Examples
        /// for Widevine details
        ///
        /*
        config.drmType = .drmToday
        config.drmSystem = .widevine
        config.drmConfiguration = DrmConfiguration()
        config.drmConfiguration?.environment = .staging
        config.drmConfiguration?.userId = "purchase"
        config.drmConfiguration?.sessionId = "default"
        config.drmConfiguration?.merchant = "client_dev"
        config.drmConfiguration?.assetId = "BBB_TEST"
        */

        player.load(config: config)

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

            /// Uncomment to debug Widevine (Widevine CDM crashes the application)
            /// OEMCrypto Write Lock - Open() calling OEMCrypto_OpenSession
            ///
            /// The initialisation of Widevine will be skipped and one will be able to build UI.
            ///
            /// or disable `Debug executable` in Scheme -> Run -> Info
            /*
            if state == .ready {
                var drm = self.player.drm
                drm?.enableDebugging = true
            }
            */
        }

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

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