//
//  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 tournamentStore: TournamentStore? {
        return self.tournament.tournamentStore
    }
    
    var body: some View {
        HStack {
            Text(player.playerLabel())
            Spacer()
            Picker(selection: $player.sex) {
                Text("Homme").tag(PlayerSexType.male as PlayerSexType?)
                Text("Femme").tag(PlayerSexType.female as PlayerSexType?)
            } label: {
                
            }
            .pickerStyle(.segmented)
            .fixedSize()
            .onChange(of: player.sex) {
                _save()
            }
        }
    }
    
    private func _save() {
        player.setComputedRank(in: tournament)
        tournamentStore?.playerRegistrations.addOrUpdate(instance: player)
        if let team = player.team() {
            team.updateWeight(inTournamentCategory: tournament.tournamentCategory)
            tournamentStore?.teamRegistrations.addOrUpdate(instance: team)
        }
    }

}

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