//
//  ViewController.swift
//  SubtitlesDemo
//
//

import PRESTOplay
import CastlabsApple
import CastlabsSubtitles
import AVFoundation
import UIKit

class ViewController: UIViewController {
    // create player instance
    var player = PRESTOplaySDK.shared.player()
    var subtitles: SubtitlesAPI?
    var subtitlesTrack: TextTrack?

    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 }

        let config = PlayerConfiguration(with: contentURL)
        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
            }

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

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

        subtitles = PRESTOplaySDK.shared.subtitles(for: player)
        subtitles?.subtitlesStyle = SubtitlesStyle(fromSystemSettings: true)
    }

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

    func addSubtitles() {
        guard let url = URL(string: "https://demo.cf.castlabs.com/media/players/presto.vtt") else {
            print("unable to parse subtitles url")
            return
        }

        subtitlesTrack = TextTrack(
            id: UUID().uuidString,
            format: .web_vtt,
            isPlatformRendered: false,
            label: "sideloaded",
            language: "en",
            sourceUrl: url)

        if let track = subtitlesTrack {
            subtitles?.addTextTrack(track) { _, error in
                if let error { print(error) } else { print("subtitles track loaded") }
                self.player.setTextTrack(track)
            }
        }
    }
}
