//
//  PlayerSexPickerView.swift
//  PadelClub
//
//  Created by Razmig Sarkissian on 24/03/2024.
//

import SwiftUI

struct PlayerSexPickerView: View {
    @EnvironmentObject var dataStore: DataStore
    @Environment(Tournament.self) var tournament: Tournament
    @Bindable var player: PlayerRegistration

    var body: some View {
        HStack {
            Text(player.playerLabel())
            Spacer()
            Picker(selection: $player.sex) {
                Text("Homme").tag(PlayerRegistration.PlayerSexType.male as PlayerRegistration.PlayerSexType?)
                Text("Femme").tag(PlayerRegistration.PlayerSexType.female as PlayerRegistration.PlayerSexType?)
            } label: {
                
            }
            .pickerStyle(.segmented)
            .fixedSize()
            .onChange(of: player.sex) {
                _save()
            }
        }
    }
    
    private func _save() {
        do {
            player.setComputedRank(in: tournament)
            try dataStore.playerRegistrations.addOrUpdate(instance: player)
            if let team = player.team() {
                team.updateWeight(inTournamentCategory: tournament.tournamentCategory)
                try dataStore.teamRegistrations.addOrUpdate(instance: team)
            }
            
        } catch {
            // Replace this implementation with code to handle the error appropriately.
            // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            let nsError = error as NSError
            fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
        }
    }

}

//#Preview {
//    PlayerSexPickerView(player: PlayerRegistration.mock())
//        .environment(Tournament.mock())
//}
