//
//  AllWorkoutsView.swift
//  Werkout_ios
//
//  Created by Trey Tartt on 6/15/23.
//

import Foundation
import SwiftUI

struct AllWorkoutsView: View {
    @State var workouts: [Workout]?
    var bridgeModule = BridgeModule.shared
    @State public var needsUpdating: Bool = true
    
    @State private var showWorkoutDetail = false
    @State private var selectedWorkout: Workout? {
        didSet {
            bridgeModule.currentWorkout = selectedWorkout
            showWorkoutDetail = true
        }
    }
    
    let pub = NotificationCenter.default.publisher(for: NSNotification.Name("CreatedNewWorkout"))
    
    var body: some View {
        ZStack {
            if let workouts = workouts {
                List {
                    ForEach(workouts, id:\.name) { workout in
                        VStack {
                            Text(workout.name)
                                .font(.title2)
                                .frame(maxWidth: .infinity, alignment: .leading)
                            Text(workout.description ?? "")
                                .frame(maxWidth: .infinity, alignment: .leading)
                        }
                        .contentShape(Rectangle())
                        .onTapGesture {
                            selectedWorkout = workout
                        }
                    }
                }
            } else {
                Text("no workouts")
            }
        }.onAppear{
            if needsUpdating {
                AllWorkoutFetchable().fetch(completion: { result in
                    needsUpdating = false
                    switch result {
                    case .success(let model):
                        DispatchQueue.main.async {
                            self.workouts = model
                        }
                    case .failure(let failure):
                        fatalError("shit broke")
                    }
                })
            }
        }
        .sheet(item: $selectedWorkout) { item in
            let viewModel = WorkoutDetailViewModel(workout: item)
            WorkoutDetailView(viewModel: viewModel)
        }
        .onReceive(pub) { (output) in
            self.needsUpdating = true
        }
    }

    func testParse() {
        if let filepath = Bundle.main.path(forResource: "AllWorkouts", ofType: "json") {
            do {
                let data = try Data(NSData(contentsOfFile: filepath))
                let workout = try JSONDecoder().decode([Workout].self, from: data)
                self.workouts = workout
            } catch {
                print(error)
                fatalError()
            }
        } else {
            fatalError()
        }
    }
}
