import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../shared/models/score_state.dart';

class ScoreNotifier extends StateNotifier<ScoreState> {
  ScoreNotifier() : super(const ScoreState());

  void reset(ScoreState score) {
    state = score;
  }

  void applyRemote(ScoreState score) {
    state = score;
  }

  void incrementHome() {
    state = state.copyWith(homePoints: state.homePoints + 1);
  }

  void incrementAway() {
    state = state.copyWith(awayPoints: state.awayPoints + 1);
  }

  void decrementHome() {
    if (state.homePoints > 0) {
      state = state.copyWith(homePoints: state.homePoints - 1);
    }
  }

  void decrementAway() {
    if (state.awayPoints > 0) {
      state = state.copyWith(awayPoints: state.awayPoints - 1);
    }
  }

  void closeSet() {
    final homeWon = state.homePoints > state.awayPoints;
    final partials = List<SetPartial>.from(state.setPartials);
    if (state.homePoints > 0 || state.awayPoints > 0) {
      partials.add(SetPartial(
        set: state.currentSet,
        home: state.homePoints,
        away: state.awayPoints,
      ));
    }
    state = state.copyWith(
      homeSets: homeWon ? state.homeSets + 1 : state.homeSets,
      awaySets: homeWon ? state.awaySets : state.awaySets + 1,
      homePoints: 0,
      awayPoints: 0,
      currentSet: state.currentSet + 1,
      setPartials: partials,
      timeoutHome: false,
      timeoutAway: false,
    );
  }

  void timeoutHome() {
    state = state.copyWith(timeoutHome: true);
  }

  void timeoutAway() {
    state = state.copyWith(timeoutAway: true);
  }

  void setTimeoutHome(bool value) {
    state = state.copyWith(timeoutHome: value);
  }

  void setTimeoutAway(bool value) {
    state = state.copyWith(timeoutAway: value);
  }
}

final scoreProvider = StateNotifierProvider<ScoreNotifier, ScoreState>(
  (ref) => ScoreNotifier(),
);
