//
//  ContentView.swift
//  WekoutThotViewer
//
//  Created by Trey Tartt on 6/18/24.
//

import SwiftUI
import AVKit
import Combine

struct ContentView: View {
    @State public var needsUpdating: Bool = true
    @State var isUpdating = false
    @ObservedObject var dataStore = DataStore.shared
    @State var nsfwVideos: [NSFWVideo]?
    @State var avPlayer = AVPlayer(url: URL(string: "https://dev.werkout.fitness/media/exercise_videos/2_Dumbbell_Lateral_Lunges.mp4")!)
    
    let videoEnded = NotificationCenter.default.publisher(for: NSNotification.Name.AVPlayerItemDidPlayToEndTime)

    var body: some View {
        VStack {
            if isUpdating {
                if isUpdating {
                    ProgressView()
                        .progressViewStyle(.circular)
                }
            } else {
                PlayerView(player: $avPlayer)
                    .onAppear{
                        avPlayer.isMuted = true
                        avPlayer.play()
                    }
                    .onReceive(videoEnded){ _ in
                        playRandomVideo()
                    }
            }
        }
        .onAppear(perform: {
            maybeUpdateShit()
        })
    }
    
    func playRandomVideo() {
        if let video = nsfwVideos?.randomElement() {
            playVideo(url: video.videoFile)
        }
    }
    
    func playVideo(url: String) {
        let url = URL(string: BaseURLs.currentBaseURL + url)
        avPlayer = AVPlayer(url: url!)
        avPlayer.isMuted = true
        avPlayer.play()
    }
    
    func maybeUpdateShit() {
        UserStore.shared.setTreyDevRegisterdUser()
        
        if UserStore.shared.token != nil{
            if UserStore.shared.plannedWorkouts.isEmpty {
                UserStore.shared.fetchPlannedWorkouts()
            }
            
            if needsUpdating {
                self.isUpdating = true
                dataStore.fetchAllData(completion: {
                    DispatchQueue.main.async {
                        guard let allNSFWVideos = dataStore.allNSFWVideos else {
                            return
                        }
                        self.nsfwVideos = allNSFWVideos
                        self.isUpdating = false
                        
                        playRandomVideo()
                    }
                    
                    self.isUpdating = false
                })
            }
        }
    }
}

#Preview {
    ContentView()
}
