using System;
using System.Collections.Generic;
using System.Linq;

namespace FishDice.LuckyDice
{
    public static class ComboRuleDefinitionLoader
    {
        public static IReadOnlyList<ComboRule> Load(IReadOnlyList<ComboRuleDefinition> definitions)
        {
            if (definitions == null)
            {
                return Array.Empty<ComboRule>();
            }

            return definitions.Select(ToRuntimeRule).ToArray();
        }

        private static ComboRule ToRuntimeRule(ComboRuleDefinition definition)
        {
            if (definition == null)
            {
                throw new ArgumentNullException(nameof(definition));
            }

            return new ComboRule(
                definition.RuleId,
                definition.Priority,
                new ComboMatcherSpec(
                    definition.MatcherType,
                    comboKey: definition.ComboKey,
                    faceKey: definition.FaceKey,
                    requiredCount: definition.RequiredCount,
                    minCount: definition.MinCount,
                    maxCount: definition.MaxCount,
                    diceCount: definition.DiceCount,
                    ofAKindCount: definition.OfAKindCount,
                    minSum: definition.MinSum,
                    maxSum: definition.MaxSum,
                    useOrderedKey: definition.UseOrderedKey),
                ToRuntimeActions(definition.Actions),
                definition.StopAfterMatched);
        }

        private static IReadOnlyList<RollActionSpec> ToRuntimeActions(IReadOnlyList<RollActionDefinition> definitions)
        {
            if (definitions == null)
            {
                return Array.Empty<RollActionSpec>();
            }

            return definitions.Select(ToRuntimeAction).ToArray();
        }

        private static RollActionSpec ToRuntimeAction(RollActionDefinition definition)
        {
            if (definition == null)
            {
                throw new ArgumentNullException(nameof(definition));
            }

            var parameters = definition.Params == null
                ? null
                : definition.Params.ToDictionary(param => param.Key, param => param.Value);

            return new RollActionSpec(definition.ActionType, parameters);
        }
    }
}
