//
//  ViewController.swift
//  SPMDemo
//
//

import AVFoundation
import UIKit

import PRESTOplay
import CastlabsApple
import CastlabsIMA

class ViewController: UIViewController {
    var player = PRESTOplaySDK.shared.player()

    var ads: AdsAPI?
    var adsView = UIView()

    override func viewDidLoad() {
        super.viewDidLoad()

        view.addSubview(adsView)
        adsView.translatesAutoresizingMaskIntoConstraints = false
        adsView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
        adsView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
        adsView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
        adsView.heightAnchor.constraint(equalTo: view.heightAnchor).isActive = true

        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 = player.error {
                print("Error \(error)")
            }
        }

        let adsSettings = AdsSettings(
            waitForAdResponse: true,
            enableDebugMode: false
        )

        ads = PRESTOplaySDK.shared.ads(for: player, settings: adsSettings)
        ads?.onAdsState = { [weak self] state in
            guard let eventType = state.adsEvent?.type else { return }
            if eventType == .loaded {
                print("Ads cue points: \(self?.ads?.adCuePoints)")
            }
        }
        ads?.onCurrentTime = { progress, duration in
            print("Ads progress: \(progress), duration: \(duration)")
        }

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

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

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

    private func requestAds() {
        var adUrl = URL(string: "https://players.castlabs.com/ads/vmap?ad=1,start&ad=00:00:10&ad=1,end")!
        ads?.requestAds(withUrl: adUrl, onView: adsView, viewController: self)
    }
}
