# frozen_string_literal: true module Codebreaker module FileStore FILE_DIRECTORY = "statistics" FILE_NAME = "statistics.yml" def save_file(game) validate_state(game.state, :win) score = load_file score << fill_game_data(game) File.write(storage_path, YAML.dump({ codebrakers: score })) end def load_file create_storage unless storage_exists? (YAML.load_file(storage_path) || {})[:codebrakers] || [] end def statistics load_file.each.sort_by { |game| [game[:attempts], game[:used_hints], game[:used_attempts]] } end def self.statistics load_file.each.sort_by { |game| [game[:attempts], game[:used_hints], game[:used_attempts]] } end private def create_storage FileUtils.mkdir_p(FILE_DIRECTORY) File.open(storage_path, "w") unless File.exist?(storage_path) end def storage_path File.join(FILE_DIRECTORY, FILE_NAME) end def storage_exists? Dir.exist?(FILE_DIRECTORY) && File.exist?(storage_path) end def fill_game_data(game) game_statistic = {} game_statistic[:name] = game.user.name game_statistic[:difficulty] = game.user.difficulty game_statistic[:attempts] = Constants::DIFFICULTIES[game.user.difficulty][:attempts] game_statistic[:hints] = Constants::DIFFICULTIES[game.user.difficulty][:hints] game_statistic.merge(user_data(game)) end def user_data(game) user = {} user[:used_attempts] = used_attempts(game) user[:used_hints] = used_hints(game) user end def used_attempts(game) Constants::DIFFICULTIES[game.user.difficulty][:attempts] - game.user.attempts end def used_hints(game) Constants::DIFFICULTIES[game.user.difficulty][:hints] - game.user.hints end end end