import 'package:flutter/material.dart';
import 'package:flutter_custom_toolbox/flutter_toolbox.dart';

import 'package:wordguessing/models/game/game.dart';
import 'package:wordguessing/models/settings/settings_game.dart';
import 'package:wordguessing/models/settings/settings_global.dart';

part 'game_state.dart';

class GameCubit extends HydratedCubit<GameState> {
  GameCubit()
      : super(GameState(
          currentGame: Game.createEmpty(),
        ));

  void updateState(Game game) {
    emit(GameState(
      currentGame: game,
    ));
  }

  void refresh() {
    final Game game = Game(
      // Settings
      gameSettings: state.currentGame.gameSettings,
      globalSettings: state.currentGame.globalSettings,
      // State
      isRunning: state.currentGame.isRunning,
      isStarted: state.currentGame.isStarted,
      isFinished: state.currentGame.isFinished,
      animationInProgress: state.currentGame.animationInProgress,
      // Base data
      word: state.currentGame.word,
      otherWords: state.currentGame.otherWords,
      images: state.currentGame.images,
      // Game data
      recentWordsKeys: state.currentGame.recentWordsKeys,
      questionsCount: state.currentGame.questionsCount,
      goodAnswers: state.currentGame.goodAnswers,
      wrongAnswers: state.currentGame.wrongAnswers,
    );
    // game.dump();

    updateState(game);
  }

  void startNewGame({
    required GameSettings gameSettings,
    required GlobalSettings globalSettings,
  }) {
    final Game newGame = Game.createNew(
      // Settings
      gameSettings: gameSettings,
      globalSettings: globalSettings,
    );

    updateState(newGame);
    nextWord();

    newGame.dump();

    updateState(newGame);
    refresh();
  }

  void quitGame() {
    state.currentGame.isRunning = false;
    refresh();
  }

  void resumeSavedGame() {
    state.currentGame.isRunning = true;
    refresh();
  }

  void deleteSavedGame() {
    state.currentGame.isRunning = false;
    state.currentGame.isFinished = true;
    refresh();
  }

  void nextWord() {
    state.currentGame.pickNewWord();
    refresh();
  }

  void checkWord(word) {
    if (state.currentGame.word.key == word.key) {
      state.currentGame.goodAnswers++;
      nextWord();
    } else {
      state.currentGame.wrongAnswers++;
    }
    refresh();
  }

  @override
  GameState? fromJson(Map<String, dynamic> json) {
    final Game currentGame = json['currentGame'] as Game;

    return GameState(
      currentGame: currentGame,
    );
  }

  @override
  Map<String, dynamic>? toJson(GameState state) {
    return <String, dynamic>{
      'currentGame': state.currentGame.toJson(),
    };
  }
}