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

import PRESTOplay
import CastlabsApple
import CastlabsDownloader
import AVFoundation
import UIKit

let streamUrl = "https://demo.cf.castlabs.com/media/prestohls/master.m3u8"

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)

        guard let contentURL = URL(string: streamUrl) else { return }
        let alreadyDownloaded = downloader.getDownloads().contains {
            $0.playerConfiguration.contentUrl == 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() {
        guard let contentURL = URL(string: streamUrl) else { return }
        let config = PlayerConfiguration(with: contentURL)

        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() {
        guard let contentURL = URL(string: streamUrl) else { return }
        let localDownload = downloader.getDownloads().first { download in
            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)
    }
}
