//
//  Court.swift
//  PadelClub
//
//  Created by Razmig Sarkissian on 23/04/2024.
//

import Foundation
import SwiftUI
import LeStorage

@Observable
class Court : ModelObject, Storable, Hashable {
    static func resourceName() -> String { return "courts" }
    static func tokenExemptedMethods() -> [HTTPMethod] { return [] }

    static func == (lhs: Court, rhs: Court) -> Bool {
        lhs.id == rhs.id
    }
    
    func hash(into hasher: inout Hasher) {
        return hasher.combine(id)
    }

    var id: String = Store.randomId()
    var index: Int
    var club: String
    var name: String?
    var exitAllowed: Bool = false
    var indoor: Bool = false
    
    init(index: Int, club: String, name: String? = nil, exitAllowed: Bool = false, indoor: Bool = false) {
        self.index = index
        self.club = club
        self.name = name
        self.exitAllowed = exitAllowed
        self.indoor = indoor
    }
    
//    internal init(club: String, name: String? = nil, index: Int) {
//        self.club = club
//        self.name = name
//        self.index = index
//    }
    
    func courtTitle() -> String {
        self.name ?? courtIndexTitle()
    }
    
    func courtIndexTitle() -> String {
        Self.courtIndexedTitle(atIndex: index)
    }
    
    static func courtIndexedTitle(atIndex index: Int) -> String {
        ("Terrain #" + (index + 1).formatted())
    }
    
    func clubObject() -> Club? {
        Store.main.findById(club)
    }
    
    override func deleteDependencies() throws {
    }
    
    enum CodingKeys: String, CodingKey {
        case _id = "id"
        case _index = "index"
        case _club = "club"
        case _name = "name"
        case _exitAllowed = "exitAllowed"
        case _indoor = "indoor"
    }
    
    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        
        try container.encode(id, forKey: ._id)
        try container.encode(index, forKey: ._index)
        try container.encode(club, forKey: ._club)
        
        if let name = name {
            try container.encode(name, forKey: ._name)
        } else {
            try container.encodeNil(forKey: ._name)
        }
        
        try container.encode(exitAllowed, forKey: ._exitAllowed)
        try container.encode(indoor, forKey: ._indoor)
    }

}
