//
//  PlayerView.swift
//  LiveApple
//
//  Created by Shadowfacts on 9/24/22.
//

import SwiftUI
import AVKit

struct PlayerView: UIViewRepresentable {
    @Environment(\.scenePhase) private var scenePhase
    let player: AVPlayer
    
    func makeUIView(context: Context) -> PlayerViewImpl {
        PlayerViewImpl(player: player, scenePhase: scenePhase)
    }
    
    func updateUIView(_ uiView: PlayerViewImpl, context: Context) {
        uiView.scenePhase = scenePhase
    }
}

class PlayerViewImpl: UIView {
    override class var layerClass: AnyClass {
        AVPlayerLayer.self
    }
    
    var playerLayer: AVPlayerLayer {
        layer as! AVPlayerLayer
    }
    
    let player: AVPlayer
    var scenePhase: ScenePhase {
        didSet {
            if scenePhase == .active {
                playerLayer.player = player
            } else {
                playerLayer.player = nil
            }
        }
    }
    
    init(player: AVPlayer, scenePhase: ScenePhase) {
        self.player = player
        self.scenePhase = scenePhase
        
        super.init(frame: .zero)
        
        playerLayer.player = player
    }
    
    required init?(coder: NSCoder) {
        fatalError()
    }
    
}
