//
//  PlayerUIView.swift
//  Werkout_ios
//
//  Created by Trey Tartt on 7/5/23.
//

import SwiftUI
import AVKit

class PlayerUIView: UIView {
    
    // MARK: Class Property
    
    let playerLayer = AVPlayerLayer()
    
    // MARK: Init
    
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    init(player: AVPlayer) {
        super.init(frame: .zero)
        self.playerSetup(player: player)
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    // MARK: Life-Cycle
    
    override func layoutSubviews() {
        super.layoutSubviews()
        playerLayer.frame = bounds
    }
    
    // MARK: Class Methods
    
    private func playerSetup(player: AVPlayer) {
        playerLayer.player = player
        player.actionAtItemEnd = .none
        layer.addSublayer(playerLayer)
        
        self.setObserver()
    }
    
    func setObserver() {
        NotificationCenter.default.removeObserver(self)
        NotificationCenter.default.addObserver(self, selector: #selector(playerItemDidReachEnd(notification:)),
                                               name: .AVPlayerItemDidPlayToEndTime,
                                               object: playerLayer.player?.currentItem)
    }
    
    @objc func playerItemDidReachEnd(notification: Notification) {
        if let playerItem = notification.object as? AVPlayerItem {
            playerItem.seek(to: .zero, completionHandler: nil)
            self.playerLayer.player?.play()
        }
    }
}

struct PlayerView: UIViewRepresentable {
    
    @Binding var player: AVPlayer
    
    func makeUIView(context: Context) -> PlayerUIView {
        return PlayerUIView(player: player)
    }
    
    func updateUIView(_ uiView: PlayerUIView, context: UIViewRepresentableContext<PlayerView>) {
        uiView.playerLayer.player = player
        
        //Add player observer.
        uiView.setObserver()
    }
}

class VideoURLCreator {
    class func otherVideoType(forVideoURL videoURL: URL) -> ThotStyle {
        var otherVideoStyle = ThotStyle.never
        if videoURL.absoluteString.contains("exercise_videos") {
            otherVideoStyle = .always
        }
        return otherVideoStyle
    }
    
    class func videoURL(thotStyle: ThotStyle, gender: String, defaultVideoURLStr: String?, exerciseName: String?, workout: Workout?) -> URL? {
        var urlString: String?
        
        if  UserStore.shared.registeredUser?.NSFWValue ?? false {
            switch thotStyle {
            case .always:
                urlString = DataStore.shared.randomVideoFor(gender: gender)
            case .never:
                urlString = defaultVideoURLStr
            case .recovery:
                if exerciseName?.lowercased() == "recover" {
                    urlString = DataStore.shared.randomVideoFor(gender: gender)
                } else {
                    urlString = defaultVideoURLStr
                }
            case .random:
                if Bool.random() {
                    urlString = DataStore.shared.randomVideoFor(gender: gender)
                } else {
                    urlString = defaultVideoURLStr
                }
            case .off:
                return nil
            }
        } else {
            urlString = defaultVideoURLStr
        }
        
        if let urlString = urlString,
           let url = URL(string: BaseURLs.currentBaseURL + urlString) {
            return url
        }
        return nil
    }
}
