//
//  DataStore.swift
//  Werkout_ios
//
//  Created by Trey Tartt on 6/19/23.
//

import Foundation

class DataStore {
    enum DataStoreStatus {
        case loading
        case idle
    }
    
    static let shared = DataStore()
    
    public private(set) var allWorkouts: [Workout]?
    public private(set) var allMuscles: [Muscle]?
    public private(set) var allEquipment: [Equipment]?
    public private(set) var allExercise: [ExerciseExercise]?
    
    public private(set) var status = DataStoreStatus.idle
    
    private let fetchAllDataQueue = DispatchGroup()
    
    public func fetchAllData() {
        status = .loading
        
        fetchAllDataQueue.enter()
        fetchAllDataQueue.enter()
        fetchAllDataQueue.enter()
        fetchAllDataQueue.enter()
        
        fetchAllDataQueue.notify(queue: .main) {
            self.status = .idle
        }
        
        AllWorkoutFetchable().fetch(completion: { result in
            switch result {
            case .success(let model):
                self.allWorkouts = model
            case .failure(let error):
                print(error)
            }
            self.fetchAllDataQueue.leave()
        })
        
        AllMusclesFetchable().fetch(completion: { result in
            switch result {
            case .success(let model):
                self.allMuscles = model.sorted(by: {
                    $0.name < $1.name
                })
            case .failure(let error):
                print(error)
            }
            self.fetchAllDataQueue.leave()
        })
        
        AllEquipmentFetchable().fetch(completion: { result in
            switch result {
            case .success(let model):
                self.allEquipment = model.sorted(by: {
                    $0.name ?? "a" < $1.name ?? "a"
                })
            case .failure(let error):
                print(error)
            }
            self.fetchAllDataQueue.leave()
        })
        
        AllExerciseFetchable().fetch(completion: { result in
            switch result {
            case .success(let model):
                self.allExercise = model.sorted(by: {
                    $0.name < $1.name
                })
            case .failure(let error):
                print(error)
            }
            self.fetchAllDataQueue.leave()
        })
    }
}
