//
//  Workout.swift
//  Werkout_ios
//
//  Created by Trey Tartt on 6/14/23.
//

import Foundation

struct Workout: Codable, Identifiable {
    let id: Int
    let name: String
    let description: String?
    let exercises: [ExerciseElement]
    let registeredUser: RegisteredUser?
    
    enum CodingKeys: String, CodingKey {
        case name, description, exercises, id
        case registeredUser = "registered_user"
    }
    
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        if let exercises = try container.decodeIfPresent([ExerciseElement].self, forKey: .exercises) {
            self.exercises = exercises
        } else {
            self.exercises = [ExerciseElement]()
        }
        
        self.name = try container.decode(String.self, forKey: .name)
        self.description = try container.decodeIfPresent(String.self, forKey: .description)
        self.registeredUser = try container.decodeIfPresent(RegisteredUser.self, forKey: .registeredUser)
        self.id = try container.decode(Int.self, forKey: .id)
    }
    
    var exercisesSortedByCreated_at: [ExerciseElement] {
        return self.exercises.sorted(by: {
            $0.createdAtDate < $1.createdAtDate
        })
    }
}
