//
//  CreateViewModels.swift
//  Werkout_ios
//
//  Created by Trey Tartt on 6/18/23.
//

import SwiftUI

class CreateWorkoutExercise: ObservableObject, Identifiable {
    let id = UUID()
    var exercise: Exercise
    @Published var reps: Int = 0
    @Published var duration: Int = 0
    @Published var weight: Int = 0
    
    init(exercise: Exercise, reps: Int = 0, duration: Int = 0, weight: Int = 0) {
        self.exercise = exercise
        self.reps = reps
        self.duration = duration
        self.weight = weight
    }
    
    func increaseReps() {
        self.reps += 1
    }
    
    func decreaseReps() {
        self.reps -= 1
        if self.reps < 0 {
            self.reps = 0
        }
    }
    
    func increaseDuration() {
        self.duration += 15
        self.reps = 0
    }
    
    func decreaseDuration() {
        self.duration -= 15
        if self.duration < 0 {
            self.duration = 0
        }
    }
    
    func increaseWeight() {
        self.weight += 5
    }
    
    func decreaseWeight() {
        self.weight -= 15
        if self.weight < 0 {
            self.weight = 0
        }
    }
}

class CreateWorkoutSuperSet: ObservableObject, Identifiable, Equatable {
    static func == (lhs: CreateWorkoutSuperSet, rhs: CreateWorkoutSuperSet) -> Bool {
        lhs.id == rhs.id
    }
    
    let id = UUID()
    @Published var exercises = [CreateWorkoutExercise]()
    @Published var numberOfRounds = 0
    
    func increaseNumberOfRounds() {
        self.numberOfRounds += 1
    }
    
    func decreaseNumberOfRounds() {
        self.numberOfRounds -= 1
        if self.numberOfRounds < 0 {
            self.numberOfRounds = 0
        }
    }
    
    func deleteExerciseForChosenSuperset(exercise: CreateWorkoutExercise) {
        if let idx = exercises.firstIndex(where: {
            $0.id == exercise.id
        }) {
            exercises.remove(at: idx)
        }
    }
}

class WorkoutViewModel: ObservableObject {
    @Published var superSets = [CreateWorkoutSuperSet]()
    @Published var title = String()
    @Published var description = String()
    @Published var randomValueForUpdatingValue = 0
    
    func increaseRandomNumberForUpdating() {
        randomValueForUpdatingValue += 1
    }
    
    func addNewSuperset() {
        increaseRandomNumberForUpdating()
        superSets.append(CreateWorkoutSuperSet())
    }
    
    func delete(superset: CreateWorkoutSuperSet) {
        if let idx = superSets.firstIndex(where: {
            $0.id == superset.id
        }) {
            superSets.remove(at: idx)
            increaseRandomNumberForUpdating()
        }
    }
    
    func showRoundsError() {
        
    }
    
    func showNoDurationOrReps() {
        
    }
    
    func uploadWorkout() {
        var supersets = [[String: Any]]()
        var supersetOrder = 1
        superSets.forEach({ superset in
            if superset.numberOfRounds == 0 {
                showRoundsError()
                return
            }
            var supersetInfo = [String: Any]()
            supersetInfo["name"] = ""
            supersetInfo["rounds"] = superset.numberOfRounds
            supersetInfo["order"] = supersetOrder
            
            var exercises = [[String: Any]]()
            var exerciseOrder = 1
            for exercise in superset.exercises {
                if exercise.reps == 0 && exercise.duration == 0 {
                    showNoDurationOrReps()
                    return
                }
                
                let item = ["id": exercise.exercise.id,
                            "reps": exercise.reps,
                            "weight": exercise.weight,
                            "duration": exercise.duration,
                            "order": exerciseOrder] as [String : Any]
                exercises.append(item)
                exerciseOrder += 1
            }
            supersetInfo["exercises"] = exercises
            
            supersets.append(supersetInfo)
            supersetOrder += 1
        })
        let uploadBody = ["name": title,
                          "description": description,
                          "supersets": supersets] as [String : Any]
        CreateWorkoutFetchable(postData: uploadBody).fetch(completion: { result in
            DispatchQueue.main.async {
                switch result {
                case .success(_):
                    self.superSets.removeAll()
                    self.title = ""
                    NotificationCenter.default.post(name: NSNotification.Name("CreatedNewWorkout"), object: nil, userInfo: nil)
                case .failure(let failure):
                    print(failure)
                }
            }
        })
    }
}
