using QuestValidator.Common.Helpers;
using QuestValidator.Common.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;

namespace QuestValidator.Common
{
    public static class ItemTemplateHelper
    {
        private static Dictionary<string, Item> _itemCache;

        public static Dictionary<string, Item> Items
        {
            get
            {
                if (_itemCache is null)
                {
                    var itemsFilePath = $"{Directory.GetCurrentDirectory()}\\Assets\\items.json";
                    if (!File.Exists(itemsFilePath))
                    {
                        throw new Exception($"Missing items.json under assets ({itemsFilePath})");
                    }

                    var itemsJson = File.ReadAllText(itemsFilePath);
                    _itemCache = JsonSerializer.Deserialize<Dictionary<string, Item>>(itemsJson);
                }

                return _itemCache;
            }
        }

        public static Item GetTemplateById(string templateId)
        {
            if (templateId == "5449016a4bdc2d6f028b456f")
            {
                return new Item
                {
                    _id = templateId,
                    _name = "Roubles",
                    _parent = "543be5dd4bdc2deb348b4569",
                    _type = ""
                };
            }

            if (templateId == "569668774bdc2da2298b4568")
            {
                return new Item
                {
                    _id = templateId,
                    _name = "Euros",
                    _parent = "543be5dd4bdc2deb348b4569",
                    _type = ""
                };
            }

            if (templateId == "5696686a4bdc2da3298b456a")
            {
                return new Item
                {
                    _id = templateId,
                    _name = "Dollars",
                    _parent = "543be5dd4bdc2deb348b4569",
                    _type = ""
                };
            }

            if (Items.ContainsKey(templateId))
            {
                return Items[templateId];
            }

            LoggingHelpers.LogToConsole($"Could not locate item template with id {templateId}", ConsoleColor.Red);
            return null;
        }
    }
}