using Model.Logic;
using System;
using System.Collections;
using System.Collections.Generic;

namespace Profile {
    public sealed class Container: IContainer {
        public readonly Dictionary<string, int> Items;

        private System.Action onUpdate = null;

        public Container(Dictionary<string, int> startItems = null) {
            Items = startItems ?? new Dictionary<string, int>();
        }
        public Container(IContainer container) {
            Items = new Dictionary<string, int>();
            foreach (var item in container)
                Items.Add(item.Key, item.Value);
        }

        public int this[string itemId] {
            get { return GetItem(itemId); }
            set { SetItem(itemId, value); }
        }

        const string randomId = "random";

        public void SetItems(Container items) {
            if (items != null && items.Items != null) {
                foreach (var item in items.Items) {
                    SetItem(item.Key, item.Value);
                }
            }
        }

        public void SetItems(Dictionary<string, int> items) {
            if (items != null) {
                foreach (var item in items) {
                    SetItem(item.Key, item.Value);
                }
            }
        }

        public int GetItem(string itemId) {
            if (itemId == String.Empty) {
                return 0;
            }
            if (itemId.StartsWith(randomId)) {
                if (!int.TryParse(itemId.Remove(0, randomId.Length), out int randomMaxValue)) {
                    randomMaxValue = 100;
                }
                return UnityEngine.Random.Range(0, randomMaxValue);
            }
            if (Items.ContainsKey(itemId))
                return Items[itemId];
            return 0;
        }

        public void SetItem(string itemId, int count = 0) {
            // Remove zero element items
            if (count == 0) {
                if (Items.ContainsKey(itemId)) {
                    Items.Remove(itemId);
                }
                UpdateResourceCount(itemId, count);
                return;
            }
            if (Items.ContainsKey(itemId)) {
                Items[itemId] = count;
            } else {
                Items.Add(itemId, count);
            }
            UpdateResourceCount(itemId, count);
        }

        private void UpdateResourceCount(string itemId, int count) {
            if (onUpdate != null) {
                onUpdate();
            }
        }

        public void SubscribeAll(System.Action onResourceUpdate) {
            onUpdate += onResourceUpdate;
        }

        IEnumerator<KeyValuePair<string, int>> IEnumerable<KeyValuePair<string, int>>.GetEnumerator() {
            return Items.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator() {
            return Items.GetEnumerator();
        }
    }
}
