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

import Foundation

struct Workout: Codable, Identifiable, Equatable {
    static func == (lhs: Workout, rhs: Workout) -> Bool {
        lhs.id == rhs.id
    }
    
    let id: Int
    let name: String
    let description: String?
    let supersets: [Superset]?
    let registeredUser: RegisteredUser?
    let muscles: [String]?
    let equipment: [String]?
    let exercise_count: Int?
    let createdAt: Date?
    let estimatedTime: Double?
    let allSupersetExecercise: [SupersetExercise]?
    
    enum CodingKeys: String, CodingKey {
        case id, name, description, supersets, exercise_count, muscles, equipment
        case registeredUser = "registered_user"
        case createdAt = "created_at"
        case estimatedTime = "estimated_time"
        case allSupersetExecercise = "all_superset_exercise"
    }
    
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)

        self.name = try container.decodeIfPresent(String.self, forKey: .name) ?? "NA"
        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)
        self.supersets = try container.decodeIfPresent([Superset].self, forKey: .supersets)
        
        self.equipment = try container.decodeIfPresent([String].self, forKey: .equipment)
        self.muscles = try container.decodeIfPresent([String].self, forKey: .muscles)
        self.exercise_count = try container.decodeIfPresent(Int.self, forKey: .exercise_count)
        
        let createdAtStr = try container.decodeIfPresent(String.self, forKey: .createdAt)
        if let createdAtStr = createdAtStr {
            let formatter = DateFormatter()
            formatter.locale = Locale(identifier: "en_US_POSIX")
            formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
            let date = formatter.date(from: createdAtStr)
            self.createdAt = date
        } else {
            self.createdAt = nil
        }
        
        self.estimatedTime = try container.decodeIfPresent(Double.self, forKey: .estimatedTime)
        
        allSupersetExecercise = try container.decodeIfPresent([SupersetExercise].self, forKey: .allSupersetExecercise)
    }
}
