//
//  ViewController.swift
//  PlaylistDemo
//
//

import PRESTOplay
import CastlabsApple
import AVFoundation
import UIKit

class ViewController: UIViewController {

    // create player instance
    var player = PRESTOplaySDK.shared.player()
    var playlist: PlaylistAPI? = nil

    // swiftlint: disable line_length
    let simplePlaylist = [
        PlayerConfiguration(with: URL(
            string: "https://demo.cf.castlabs.com/media/QA/hls-short-multiaudio-multisub/playlist.m3u8")!),
        PlayerConfiguration(with: URL(
            string: "https://devstreaming-cdn.apple.com/videos/streaming/examples/bipbop_4x3/bipbop_4x3_variant.m3u8")!),
        PlayerConfiguration(with: URL(
            string: "https://devstreaming-cdn.apple.com/videos/streaming/examples/bipbop_16x9/bipbop_16x9_variant.m3u8")!)
    ]
    // swiftlint: enable line_length

    override func viewDidLoad() {
        super.viewDidLoad()

        let leftSwipe = UISwipeGestureRecognizer(
            target: self, action: #selector(moveToNextItem(_:))
        )
        
        let rightSwipe = UISwipeGestureRecognizer(
            target: self, action: #selector(moveToNextItem(_:))
        )

        leftSwipe.direction = .left
        rightSwipe.direction = .right

        view.addGestureRecognizer(leftSwipe)
        view.addGestureRecognizer(rightSwipe)

        let messageLabel = UILabel()
        messageLabel.text = "Swipe left or right to change playlist item"
        messageLabel.font = .systemFont(ofSize: 16.0)
        messageLabel.textAlignment = .center
        messageLabel.center = CGPoint(x: 30.0, y: 80.0)
        messageLabel.sizeToFit()
        view.addSubview(messageLabel)

        // Do any additional setup after loading the view.
        // optional: ignore silent switch
        try? AVAudioSession.sharedInstance().setCategory(.playback)

        playlist = PRESTOplaySDK.shared.playlist(for: player, mode: .nativeQueue)
        playlist?.load(items: simplePlaylist)

        player.onState = { [weak self] previous, state in
            guard let self else { return }
            if let error = player.error {
                print("Error \(error)")
            }
        }

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

        print("Number of items in the playlist: \(playlist?.getSize() ?? -1)")
        print("Current playlist item: \(playlist?.getCurrentItemIndex() ?? -1)")
    }

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

    @objc 
    func moveToNextItem(_ sender: UISwipeGestureRecognizer) {
        switch sender.direction {
        case .left:
            playlist?.nextItem()
        case .right:
            playlist?.previousItem()
        default: break
        }

        print("Current playlist item: \(playlist?.getCurrentItemIndex() ?? -1)")
    }
}
