//
//  ViewController.swift
//  YouboraDemo
//
//

import PRESTOplay
import CastlabsApple
import CastlabsYoubora
import AVFoundation
import UIKit
import NpawPlugin

class ViewController: UIViewController {
    // create player instance
    var player = PRESTOplaySDK.shared.player()
    var analytics: AnalyticsAPI?

    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
            }
        }
        
        addYoubora()

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

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

    func addYoubora() {
        analytics = PRESTOplaySDK.shared.analytics(for: player, .youbora)
        let youboraMetadata = YouboraMetadata(
            live: false,
            assetId: "assetId")
        youboraMetadata.analyticsOptions = NpawPlugin.AnalyticsOptions()
        youboraMetadata.analyticsOptions?.adCustomDimension1 = "test"
        youboraMetadata.analyticsOptions?.contentTitle = "test"
        youboraMetadata.analyticsOptions?.autoDetectBackground = false
        youboraMetadata.analyticsOptions?.userName = "User Name"
        youboraMetadata.accountCode = "ACCOUNT_CODE"
        analytics?.metadata = youboraMetadata
    }
}
