using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using UnityEngine.SceneManagement;
using System.IO;
using System.Linq;

public class SceneInventoryManager : MonoBehaviour
{
    private const string DYNAMIC_ELEMENT = "/DynamicElements/";
    private const string STATIC_ELEMENT = "/StaticElements/";

    [SerializeField]
    public Dictionary<int, EquippableItemPrefarbAsset> ItemsElements = new Dictionary<int, EquippableItemPrefarbAsset>();

    public bool isNewGame = true; 
    public bool isContinued = false;
    public string MapName;
    public string ElementFolderName = "InventoryItem";
    public string ItemsListName = "InventoryItemList";

    public static SceneInventoryManager Instance;

    public void Awake()
    {
        if(Instance == null)
        {
            this.MapName = SceneManager.GetActiveScene().name;

            Instance = this;


        }else if (Instance != this)
        {
            Destroy(gameObject);
        }
    }

    public void Start()
    {
        LoadInventoryItems();  // load user items

        foreach(KeyValuePair<int, EquippableItemPrefarbAsset> ItemsElements in ItemsElements)
        {
            Debug.Log("Content:" + ItemsElements.Value.equippableItem.Name);
        }
        BuildInventoryItems(ItemsElements); // pass them to InventoryManager
    }

        ///<summary>
    /// Pass quest to taskManager after load data
    ///</summary>
    public void BuildInventoryItems(Dictionary<int, EquippableItemPrefarbAsset> itemsList)
    {
        // pass to InventoryManager singleton
        foreach(KeyValuePair<int, EquippableItemPrefarbAsset> itemEntry  in itemsList)
            InventoryManager.Instance.SetupItemInInventory(itemEntry.Key, itemEntry.Value.equippableItem);
    }

    public void RemoveInventoryItems(string _name)
    {
        // 1. Fetch all matched quests - we search by title which shoudl be unique but who know :D
        List<int> itemsList = this.ItemsElements.Where(item => item.Value.name == _name).Select(item => item.Key).ToList();

        // 2. Remove them
        foreach(var item in this.ItemsElements.Where(item => item.Value.name == _name).ToList())
        {
            this.ItemsElements.Remove(item.Key);
        }
    }

    ///<summary>
    /// Use TaskManaager list to save user quests - TaskManager.Instance.taskList
    ///</summary>
    public void SaveInventoryItems()
    {
        // Case I - if we remember all list
        //      1) if after removed item form DynamicList is empty - remove all file
        //      2) if after removed item form DynamciList there are another one - save updated list again
        if(InventoryManager.Instance._items.Count > 0) {
            // 1. Map From Dictionary<int, Item>' to 'Dictionary<int, EquippableItemPrefarbAsset>'
            Dictionary<int, EquippableItemPrefarbAsset> mappedList = new Dictionary<int, EquippableItemPrefarbAsset>();

            foreach(KeyValuePair<int, Item> itemElement in InventoryManager.Instance._items)
            {
                mappedList[itemElement.Key] = new EquippableItemPrefarbAsset(
                    itemElement.Value.Name,
                    itemElement.Value.ItemModel.name,
                    new Vector3(0,0,0),
                    (EquippableItem) itemElement.Value
                );
            }

            // 2. Save Items
            SaveInventorySystem.SaveInventoryItemsList(mappedList, this.ItemsListName);
        } else {
            string _path = SaveSystem.GetSavePath() + "/" + this.ItemsListName + ".fun";
            
            try    
            {    
                Debug.Log("File to remove: " + _path);

                if(File.Exists(_path))
                {
                    File.Delete(_path);
                }    
            }    
            catch (IOException ioExp)    
            {    
                Debug.LogError(ioExp.Message);    
            }
        }

        // Case II - if we rememenber object per file 
        //      1) remove specyfic file
        //
        // Unfortunatelly we don't use this way of saving items yet :D
    }

    ///<summary>
    /// Load quests to local list
    /// Pass this to taskManager in outside method
    ///</summary>
    public void LoadInventoryItems()
    {
        this.LoadInventoryItemsList();
    }

    public void LoadInventoryItemsList()
    {
        string path = SaveSystem.GetSavePath();

        if (!Directory.Exists(path))    // if not exists thats mean there was nothing saved yet - nothing to load
            return;

        FileInfo[] fileInfo = new DirectoryInfo(path).GetFiles();

        foreach(FileInfo file in fileInfo)
        {
            if(file.Name != this.ItemsListName + ".fun")
                continue;

            Dictionary<int, EquippableItemPrefarbAssetData> equippableItemsList = SaveInventorySystem.LoadInventoryItemsList(this.ItemsListName);

            // itemEntry.Value.MapDataToEquippableItem() - map data format to object 

            // save object
            foreach(KeyValuePair<int, EquippableItemPrefarbAssetData> itemEntry  in equippableItemsList)
            {
                InventoryManager.Instance.SetupItemInInventory(itemEntry.Key, itemEntry.Value.MapDataToEquippableItemPrefarbAsset().equippableItem);
            }
                
        }
    }
}