//
//  PlayerView.swift
//  Demos
//

import AVFoundation
import SwiftUI
import PRESTOplay

struct PlayerView: View {
    // describe the demo configuration
    let demo: Demo
    // create player instance
    @State private var player: PlayerAPI?
    @State private var position: Double = 0
    @State private var thumbnailsVisible: Bool = false
    @State private var thumbnail: UIImage = UIImage()
    @State private var playerUIView: PlayerUIView?

    var body: some View {
        VStack {
            if let playerUIView {
                playerUIView.onTapGesture {
                    guard let player else { return }
                    player.playbackState == .playing ? player.pause() : player.play()
                }
            } else {
                EmptyView()
            }

            if thumbnailsVisible {
                Image(uiImage: thumbnail)
                    .resizable()
                    .frame(maxWidth: 140.0, maxHeight: 80.0)
            }

            #if !os(tvOS)
            Slider(value: $position, in: 0...100) { editing in
                guard !editing else { return }
                guard let player else { return }

                /// this is only a simple demo, please use seekable timeranges to seek
                /// demo present how can thumbnails be implemented
                let value = position / 100.0 * player.duration
                let time = CMTime(seconds: value, preferredTimescale: 1000)
                player.seek(time)
            }
            .padding(15.0)
            #endif
        }
        .onAppear() {
            let player = PRESTOplaySDK.shared.player()
            let playerUIView = PlayerUIView(
                demo: demo,
                player: player,
                position: $position,
                thumbnailsVisible: $thumbnailsVisible,
                thumbnail: $thumbnail
            )
            self.player = player
            self.playerUIView = playerUIView
        }
        .onDisappear {
            player?.stop()
        }

        #if !os(tvOS)
        .navigationBarTitle(Text(demo.title), displayMode: .inline)
        #endif
    }
}

struct PlayerView_Previews: PreviewProvider {
    static var previews: some View {
        PlayerView(demo: Demo(
            title: "HLS Playback",
            description: "Basic HLS playback demo"
        ))
    }
}
