//
//  ViewController.swift
//  DownloaderDemo
//
//

import PRESTOplay
import CastlabsApple
import CastlabsDownloader
import AVFoundation
import UIKit

// change to protected to test DRM download
let playerConfiguration = TestAssets.clearStream

class TestAssets {
    static let clearStream =
        PlayerConfiguration(
            with: URL(
                string: "https://demo.cf.castlabs.com/media/prestohls/master.m3u8")!)

    static var protectedStream: PlayerConfiguration {
        let config =
            PlayerConfiguration(
                with: URL(string: "https://demo.cf.castlabs.com/media/fps/prog_index.m3u8")!)
        config.drmConfiguration = DrmConfiguration()
        config.drmType = .drmToday
        config.drmConfiguration?.environment = .staging
        config.drmConfiguration?.userId = "purchase"
        config.drmConfiguration?.sessionId = "session"
        config.drmConfiguration?.merchant = "six"
        config.drmConfiguration?.assetId = "twelve"
        config.drmConfiguration?.variantId = nil
        config.drmConfiguration?.authToken = nil
        config.drmConfiguration?.persistLicense = true
        config.drmSystem = .fairplay
        return config
    }
}

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

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        // optional: ignore silent switch
        try? AVAudioSession.sharedInstance().setCategory(.playback)

        let alreadyDownloaded = downloader.getDownloads().contains {
            $0.playerConfiguration.contentUrl == playerConfiguration.contentUrl
        }

        if alreadyDownloaded {
            print("The stream is already downloaded")
            play()
        } else {
            print("Starting the stream download")
            download()
        }
    }

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

    func download() {
        let config = playerConfiguration

        if config.contentUrl == TestAssets.protectedStream.contentUrl {
            let prefetcher = PRESTOplaySDK.shared.prefetcher(for: config)
            prefetcher?.prefetchKeys { error in
                guard error == nil else {
                    print("Error: \(error?.message ?? "Unknown prefetch error")")
                    return
                }
                print("License prefetching completed")
            }
        }

        let download = downloader.createDownload(config, headers: [:])
        downloader.prepareDownload(download.uuid, completion: { download, error in
            if let error = error {
                print("Error:", error.message)
                return
            }

            guard let id = download?.uuid else { return }
            if let startError = self.downloader.startDownload(id, delegate: self) {
                print("Error:", startError.message)
            }
        })
    }

    func didStateChange(_ download: Download) {
        if download.state == .success {
            play()
        }
    }

    func didProgressChange(_ download: Download) {
        print("Progress: \(download.progress.percent)")
    }

    func play() {
        let localDownload = downloader.getDownloads().first { download in
            playerConfiguration.contentUrl == download.playerConfiguration.contentUrl
        }
        guard let download = localDownload else { return }
        let config = try! PlayerConfiguration(with: download)

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

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