//
//  ViewController.swift
//  ThumbnailsDemo
//
//

import PRESTOplay
import CastlabsApple
import CastlabsThumbnails
import AVFoundation
import UIKit

let THUMBNAILS_WIDTH = 120
let THUMBNAILS_HEIGHT = 80

class ViewController: UIViewController {
    // create player instance
    var player = PRESTOplaySDK.shared.player()
    var thumbnails: ThumbnailsAPI?
    var thumbnailsView: UIImageView?

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        // optional: ignore silent switch
        thumbnailsView = UIImageView(frame: CGRect(x: 0, y: 0,
                                                   width: THUMBNAILS_WIDTH,
                                                   height: THUMBNAILS_HEIGHT))
        thumbnailsView?.layer.borderWidth = 5
        thumbnailsView?.layer.borderColor = UIColor.black.cgColor
        view.addSubview(thumbnailsView!)

        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
            }
        }
        
        player.onCurrentTime(rate: 1.0) { position in
            if let thumb = self.thumbnails?.getThumbnail(
                atTimestamp: CMTime(seconds: position , preferredTimescale: 1)) {

                let image = UIImage.init(data: thumb.imageData)
                DispatchQueue.main.async {
                    self.thumbnailsView?.image = image

                    /// animate thumbnails
                    let nX = (position / self.player.duration) *
                    (self.view.frame.width - CGFloat(THUMBNAILS_WIDTH))

                    let nY = self.view.center.y
                    self.thumbnailsView?.frame = CGRect(x: Int(nX), y: Int(nY),
                                                        width: THUMBNAILS_WIDTH,
                                                        height: THUMBNAILS_HEIGHT)
                    self.view.bringSubviewToFront(self.thumbnailsView!)
                }
            }
        }
        
        self.addThumbnails()

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

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

    func addThumbnails() {
        thumbnails = PRESTOplaySDK.shared.thumbnails(for: player)

        guard let url = URL(string: "https://demo.castlabs.com/media/TOS/thumbs/thumbs.vtt") else {
            print("unable to parse thumbnails url")
            return
        }

        thumbnails?.loadThumbnailsFrom(webVTTtrack: url, completionHandler: { error in
            if let error { print(error) } else { print("thumbnails loaded") }
        })
    }
}
