/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.autobet.ai;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import org.autobet.model.Game;
import org.autobet.model.Team;
import org.autobet.util.GamesProcessorDriver;

import java.sql.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import static org.autobet.ImmutableCollectors.toImmutableList;

public class TeamRaterStatsCollector
{
    public enum GameResult
    {
        WIN, DRAW, LOSE
    }

    private final GamesProcessorDriver gamesProcessorDriver;
    private final TeamRater teamRater;

    public TeamRaterStatsCollector(GamesProcessorDriver gamesProcessorDriver, TeamRater teamRater)
    {
        this.gamesProcessorDriver = gamesProcessorDriver;
        this.teamRater = teamRater;
    }

    public TeamRaterStats collect(Optional<Integer> limit)
    {
        return gamesProcessorDriver.driveProcessors(GameProcessor::new, TeamRaterStats::merge, limit);
    }

    private class GameProcessor
            implements GamesProcessorDriver.GamesProcessor<TeamRaterStats>
    {
        private final TeamRaterStats.Builder builder = TeamRaterStats.builder();

        @Override
        public void process(Game game)
        {
            Team homeTeam = Team.findById(game.getLong("home_team_id"));
            Team awayTeam = Team.findById(game.getLong("away_team_id"));
            Date playedAt = game.getDate("played_at");

            Optional<Integer> homeTeamRate = teamRater.rate(homeTeam, playedAt);
            Optional<Integer> awayTeamRate = teamRater.rate(awayTeam, playedAt);

            if (homeTeamRate.isPresent() && awayTeamRate.isPresent()) {
                int rateDiff = homeTeamRate.get() - awayTeamRate.get();

                String fullTimeResult = game.getString("full_time_result");
                switch (fullTimeResult) {
                    case "H":
                        builder.incrementHome(rateDiff, GameResult.WIN);
                        break;
                    case "D":
                        builder.incrementHome(rateDiff, GameResult.DRAW);
                        break;
                    case "A":
                        builder.incrementHome(rateDiff, GameResult.LOSE);
                        break;

                    default:
                        throw new IllegalStateException("Unknown full time game result: " + fullTimeResult);
                }
            }
        }

        @Override
        public TeamRaterStats finish()
        {
            return builder.build();
        }
    }

    public static class TeamRaterStats
    {
        private final Map<Integer, RateStats> homeStats;

        public static Builder builder()
        {
            return new Builder();
        }

        @JsonCreator
        private TeamRaterStats(@JsonProperty("homeStats") Map<Integer, RateStats> homeStats)
        {
            this.homeStats = ImmutableMap.copyOf(homeStats);
        }

        public Optional<RateStats> getHome(int rate)
        {
            return Optional.ofNullable(homeStats.get(rate));
        }

        @JsonProperty("homeStats")
        public Map<Integer, RateStats> getHomeStats()
        {
            return homeStats;
        }

        @JsonIgnore
        public List<Integer> getRates()
        {
            return homeStats.keySet()
                    .stream()
                    .sorted()
                    .collect(toImmutableList());
        }

        @JsonIgnore
        public int getCount()
        {
            return getRates().stream()
                    .map(rate -> homeStats.get(rate).getCount())
                    .reduce((x, y) -> x + y)
                    .orElse(0);
        }

        public TeamRaterStats merge(TeamRaterStats other)
        {
            TeamRaterStats.Builder builder = builder();
            for (TeamRaterStats stats : ImmutableList.of(this, other)) {
                for (int rate : stats.homeStats.keySet()) {
                    RateStats rateStats = stats.homeStats.get(rate);
                    for (GameResult gameResult : GameResult.values()) {
                        builder.addHome(rate, gameResult, rateStats.get(gameResult));
                    }
                }
            }
            return builder.build();
        }

        public static class Builder
        {
            private final Map<Integer, RateStats> homeStats = new HashMap<>();

            public Builder incrementHome(int rate, GameResult gameResult)
            {
                return addHome(rate, gameResult, 1);
            }

            public Builder addHome(int rate, GameResult gameResult, int count)
            {
                RateStats value = RateStats.builder().add(gameResult, count).build();
                homeStats.merge(rate, value, RateStats::merge);
                return this;
            }

            public TeamRaterStats build()
            {
                return new TeamRaterStats(homeStats);
            }
        }
    }

    public static class RateStats
    {
        public static Builder builder()
        {
            return new Builder();
        }

        private final Map<GameResult, Integer> stats;

        @JsonCreator
        public RateStats(@JsonProperty("stats") Map<GameResult, Integer> stats)
        {
            this.stats = ImmutableMap.copyOf(stats);
        }

        @JsonIgnore
        public int getCount()
        {
            return stats.values().stream()
                    .reduce((x, y) -> x + y)
                    .orElse(0);
        }

        @JsonIgnore
        public int getWins()
        {
            return get(GameResult.WIN);
        }

        @JsonIgnore
        public int getDraws()
        {
            return get(GameResult.DRAW);
        }

        @JsonIgnore
        public int getLoses()
        {
            return get(GameResult.LOSE);
        }

        @JsonIgnore
        public int get(GameResult gameResult)
        {
            Integer gameResultStats = stats.get(gameResult);
            return gameResultStats == null ? 0 : gameResultStats;
        }

        public RateStats merge(RateStats other)
        {
            Builder builder = builder();
            for (RateStats rateStats : ImmutableList.of(this, other)) {
                for (GameResult gameResult : GameResult.values()) {
                    builder.add(gameResult, rateStats.get(gameResult));
                }
            }
            return builder.build();
        }

        @JsonProperty("stats")
        public Map<GameResult, Integer> getStats()
        {
            return stats;
        }

        public static class Builder
        {
            private Map<GameResult, Integer> stats = new HashMap<>();

            private Builder add(GameResult result, int count)
            {
                stats.merge(result, count, (left, right) -> left + right);
                return this;
            }

            public RateStats build()
            {
                return new RateStats(stats);
            }
        }
    }
}

@@ -1968,32 +1968,185 @@
 game)%0A        %7B%0A
+            String fullTimeResult = game.getString(%22full_time_result%22);%0A            if (fullTimeResult == null) %7B%0A                return;%0A            %7D%0A%0A
             Team
@@ -2641,85 +2641,8 @@
 t();
-%0A%0A                String fullTimeResult = game.getString(%22full_time_result%22);
 %0A   

Fix NPE during stats collection