//
//  ViewController.swift
//  AirPlayDemo
//
//

import PRESTOplay
import CastlabsApple
import AVFoundation
import UIKit
import AVKit

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.addAirPlay()
            }
        }

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

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

    func addAirPlay() {
        cast = PRESTOplaySDK.shared.cast(for: player, engine: .airplay)
        cast?.onCastState = { [weak self] state in
            guard let self else { return }
            print("<<<< AirPlay state: \(state)")
            switch state {
            case .ready:
                if let castButton = cast?.button,
                   let airPlayButton = castButton as? AVRoutePickerView {
                    airPlayButton.prioritizesVideoDevices = true

                    DispatchQueue.main.async {
                        airPlayButton.frame = CGRect(
                            x: 30.0,
                            y: 150.0,
                            width: 30.0,
                            height: 30.0
                        )
                        airPlayButton.center = self.view.center
                        self.view.addSubview(airPlayButton)
                    }
                }
            case .sessionStart: break
            case .sessionResume: break
            case .sessionEnd: break
            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
            case .error: break
            @unknown default: break
            }
        }
    }
}
