//
//  ViewController.swift
//  AppleThumbnailsDemo
//
//

import AVFoundation
import CastlabsApple
import PRESTOplay
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: UIView?
    var isThumbnailSeeking = false

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        // optional: ignore silent switch
        thumbnailsView = UIView(
            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://castlabs-dl.s3.amazonaws.com/public/Transcodes/Testcontent/120min/STREAMING/HLS_clear_segmented/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
            DispatchQueue.main.async { [weak self] in
                guard let self else { return }
                guard !isThumbnailSeeking else { return }
                isThumbnailSeeking = true
                thumbnails?.getThumbnail(
                    atTimestamp: position,
                    renderOn: thumbnailsView!) { error in
                        DispatchQueue.main.async {
                            self.isThumbnailSeeking = false
                        }
                    }

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

                let nY = self.view.center.y
                thumbnailsView?.frame = CGRect(
                    x: Int(nX), y: Int(nY),
                    width: THUMBNAILS_WIDTH,
                    height: THUMBNAILS_HEIGHT)
                view.bringSubviewToFront(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, engine: .apple)
    }
}
