//
//  Club.swift
//  PadelClub
//
//  Created by Laurent Morvillier on 02/02/2024.
//

import Foundation
import SwiftUI
import LeStorage

@Observable
final class Club: BaseClub {
    
    static var copyServerResponse: Bool { return true }
    
    func clubTitle(_ displayStyle: DisplayStyle = .wide) -> String {
        switch displayStyle {
        case .wide, .title:
            return name
        case .short:
            return acronym
        }
    }
    
    func shareURL() -> URL? {
        return URL(string: URLs.main.url.appending(path: "?club=\(id)").absoluteString.removingPercentEncoding!)
    }
        
    var customizedCourts: [Court] {
        DataStore.shared.courts.filter { $0.club == self.id }.sorted(by: \.index)
    }

    override func deleteDependencies() {
        let customizedCourts = self.customizedCourts
        for customizedCourt in customizedCourts {
            customizedCourt.deleteDependencies()
        }
        DataStore.shared.courts.deleteDependencies(customizedCourts)
    }

}

extension Club {
    var isValid: Bool {
        name.isEmpty == false && name.count > 3
    }
    
    func automaticShortName() -> String {
        name.acronym()
    }
    
    enum AcronymMode: String, CaseIterable {
        case automatic = "Automatique"
        case custom = "Personalisée"
    }
    
    func shortNameMode() -> AcronymMode {
        (acronym.isEmpty || acronym == automaticShortName()) ? .automatic : .custom
    }
    
    func hasTenupId() -> Bool {
        code != nil
    }
    
    func federalLink() -> URL? {
        guard let code else { return nil }
        return URL(string: "https://tenup.fft.fr/club/\(code)")
    }
    
    func courtName(atIndex courtIndex: Int) -> String {
        courtNameIfAvailable(atIndex: courtIndex) ?? Court.courtIndexedTitle(atIndex: courtIndex)
    }
    
    func courtNameIfAvailable(atIndex courtIndex: Int) -> String? {
        customizedCourts.first(where: { $0.index == courtIndex })?.name
    }
    
    func update(fromClub club: Club) {
        self.acronym = club.acronym
        self.name = club.name
        self.phone = club.phone
        self.code = club.code
        self.address = club.address
        self.city = club.city
        self.zipCode = club.zipCode
        self.latitude = club.latitude
        self.longitude = club.longitude
    }
    
    func hasBeenCreated(by creatorId: String?) -> Bool {
        return creatorId == creator || creator == nil || self.relatedUser == creatorId
    }
    
    func isFavorite() -> Bool {
        return DataStore.shared.user.clubs.contains(where: { $0 == self.id })
    }
    
    static func findOrCreate(name: String, code: String?, city: String? = nil, zipCode: String? = nil) -> Club {
        
        /*
         
         identify a club : code, name, ??
         
         */
        let club: Club? = DataStore.shared.clubs.first(where: { (code == nil && $0.name == name && $0.city == city && $0.zipCode == zipCode) || code != nil && $0.code == code })

        if let club {
            return club
        } else {
            let club = Club(creator: StoreCenter.main.userId, name: name, acronym: name.acronym(), code: code, city: city, zipCode: zipCode)
            club.relatedUser = StoreCenter.main.userId
            return club
        }
    }
    
}
