using System;
using System.Collections.Generic;

namespace FishDice.LuckyDice
{
    public interface IRandomPoolStateStore
    {
        RandomPoolState Load(string poolId, string layerId);

        void Save(RandomPoolState state);
    }

    public sealed class InMemoryRandomPoolStateStore : IRandomPoolStateStore
    {
        private readonly Dictionary<string, RandomPoolState> _states =
            new Dictionary<string, RandomPoolState>(StringComparer.Ordinal);

        public RandomPoolState Load(string poolId, string layerId)
        {
            RandomPoolState state;
            return _states.TryGetValue(ToKey(poolId, layerId), out state)
                ? state
                : new RandomPoolState(poolId, layerId, luckValue: 0, rollCount: 0);
        }

        public void Save(RandomPoolState state)
        {
            if (state == null)
            {
                throw new ArgumentNullException(nameof(state));
            }

            _states[ToKey(state.PoolId, state.LayerId)] = state;
        }

        public static string ToKey(string poolId, string layerId)
        {
            return poolId + "|" + layerId;
        }
    }
}
