//
//  PlayerUIViewController.swift
//  Demos
//

import Foundation
import SwiftUI
import PRESTOplay

struct PlayerUIViewController: UIViewControllerRepresentable {
    typealias UIViewControllerType = PlayerOwnerViewController

    let demo: Demo

    func makeUIViewController(context: Context) -> PlayerOwnerViewController {
         return PlayerOwnerViewController(demo)
    }

    func updateUIViewController(_ uiViewController: PlayerOwnerViewController, context: Context) {
        // Updates the state of the specified view controller with new information from SwiftUI.
    }
}

class PlayerOwnerViewController: UIViewController {
    let demo: Demo
    var player = PRESTOplaySDK.shared.player()
    static var ads: AdsAPI?

    init(_ demo: Demo) {
        self.demo = demo
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidAppear(_ animated: Bool) {
        guard let url = demo.url else { return }
        guard let contentURL = URL(string: url) else { return }

        player.load(config: PlayerConfiguration(with: contentURL))
        player.onState = { [weak self] previous, state in
            guard let self else { return }

            if let error = self.player.error {
                print("Error \(error)")
            }

            switch state {
            case .ready:
                self.player.play()
            default: break
            }
        }
        player.attach(to: view.layer)
        player.open(autoplay: false)

        if demo.adsEnabled == true {
            addAds()
        }
    }

    override func viewDidDisappear(_ animated: Bool) {
        player.stop()
    }

    func addAds() {
        guard let ads = PRESTOplaySDK.shared.ads(for: player)  else { return }

        let adsView = UIView(frame: view.bounds)
        view.addSubview(adsView)

        let url = URL(string: "https://players.castlabs.com/ads/vmap?ad=1,start&ad=00:00:30&ad=1,end")!
        ads.requestAds(withUrl: url, onView: adsView, viewController: self)
        Self.ads = ads
    }
}
