//
//  ViewController.swift
//  ChromecastDemo
//
//

import PRESTOplay
import CastlabsApple
import CastlabsChromecast
import AVFoundation
import UIKit

class ViewController: UIViewController {
    // create player instance
    var player = PRESTOplaySDK.shared.player()
    var playerConfig: PlayerConfiguration?
    // mind all the settings added to app Info.plist
    var cast: CastAPI?

    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: "https://demo.cf.castlabs.com/media/prestohls/master.m3u8")
        else { return }

        playerConfig = PlayerConfiguration(with: contentURL)
        if let config = playerConfig {
            player.load(config: config)
        }

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

            if state == .ready {
                self.addChromecast()
            }
        }

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

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

    func addChromecast() {
        let appId = "6BF5C590"
        let castSettings = CastSettings(appId)
        castSettings.debug = true

        cast = PRESTOplaySDK.shared.cast(for: castSettings)
        cast?.onCastState = { [weak self] state in
            guard let self else { return }
            switch state {
            case .ready:
                if let castButton = cast?.button {
                    DispatchQueue.main.async {
                        castButton.center = self.view.center
                        self.view.addSubview(castButton)
                    }
                }
            case .sessionStart:
                if let config = playerConfig {
                    self.player.pause()
                    cast?.load(config)
                }
            case .sessionResume: break
            case .sessionEnd:
                self.player.play()
            case .unknown: break
            case .idle: break
            case .playing:
                print("Tracks: \(String(describing: cast?.tracks))")
            case .paused: break
            case .buffering: break
            case .loading: break
            case .sessionStarting: break
            @unknown default: break
            }
        }
    }
}
