From a842e0db3c5869d5142d87ee650ef488b718c321 Mon Sep 17 00:00:00 2001 From: Malaber <32635600+Malaber@users.noreply.github.com> Date: Wed, 24 Apr 2019 12:29:46 +0200 Subject: [PATCH] Add group stage service This service is responsible for all actions concerning the group stage It returns false if no groups are given to generate_group_stage method This prevents dividing by zero in the next line --- app/services/group_stage_service.rb | 37 +++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 app/services/group_stage_service.rb diff --git a/app/services/group_stage_service.rb b/app/services/group_stage_service.rb new file mode 100644 index 0000000..2e93f76 --- /dev/null +++ b/app/services/group_stage_service.rb @@ -0,0 +1,37 @@ +# frozen_string_literal: true + +class GroupStageService + def self.generate_group_stage(groups) + return false if groups.length.zero? + + average_group_size = (groups.flatten.length.to_f / groups.length.to_f) + if (average_group_size % 1).zero? + groups = groups.map { |group| get_group_object_from(group) } + group_stage = Stage.new level: -1, groups: groups + group_stage + else + false + end + end + + def self.get_group_object_from(team_array) + matches = generate_all_matches_between team_array + group = Group.new matches: matches + group + end + + def self.generate_all_matches_between(teams) + matches = [] + matchups = teams.combination(2).to_a + matchups.each_with_index do |matchup, i| + match = Match.new state: :not_started, + position: i, + match_scores: [ + MatchScore.create(team: matchup.first), + MatchScore.create(team: matchup.second) + ] + matches << match + end + matches + end +end