//
//  ViewController.swift
//  IMADemo
//
//

import PRESTOplay
import CastlabsApple
import CastlabsIMA
import AVFoundation
import UIKit

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

    // Option 1 and 2
//    let adsView = UIView()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Option 1: Layout with subview
//        view.addSubview(adsView)
//        adsView.frame = view.bounds

        // Option 2: Layout with Auto Layout
//        view.addSubview(adsView)
//        adsView.translatesAutoresizingMaskIntoConstraints = false
//        NSLayoutConstraint.activate([
//            adsView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
//            adsView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor),
//            adsView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor),
//            adsView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor)
//        ])

        // 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
            }

            switch state {
            case .ready:
                self.player.play()
            default: break
            }

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

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        requestAds()
    }

    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        player.update(size: size)
    }
    
    func setupAds() {
        ads = PRESTOplaySDK.shared.ads(for: player)
        ads?.onAdsState = { state in
            print("Ad event type: \(state.adsEvent?.type)")
        }
    }

    func requestAds() {
        let url = URL(string: "https://players.castlabs.com/ads/vmap?ad=1,start&ad=00:00:30&ad=1,end")!
        // Option 0: Layout with main view
        ads?.requestAds(withUrl: url, onView: view, viewController: self)

        // Option 1 and 2
//        ads?.requestAds(withUrl: url, onView: adsView, viewController: self)
    }
}
