using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace PlantBox.Broker
{
    class PlantBoxesManager : IEnumerable<PlantBox>
    {
        public string FilePath => Path.Combine(Environment.CurrentDirectory, FileName);
        public string FileName => "storage.json";

        private Dictionary<ulong, PlantBox> _plantBoxes;

        public PlantBoxesManager()
        {

        }

        public PlantBox this[ulong id]
        {
            get => _plantBoxes.GetValueOrDefault(id);
        }

        public PlantBox GetPlantBox(ulong id) => this[id];

        public void Add(PlantBox plantBox)
        {
            ulong id = plantBox.ID;
            if (_plantBoxes.ContainsKey(id))
            {
                _plantBoxes[id] = plantBox;
            }
            else
            {
                _plantBoxes.Add(id, plantBox);
            }
        }

        public void UpdatePlantsState()
        {
            foreach (PlantBox plantBox in _plantBoxes.Values)
            {
                plantBox.UpdateState();
            }
        }

        public void Load()
        {
            Console.WriteLine("Loading storage...");

            if (File.Exists(FilePath))
            {
                _plantBoxes = JsonConvert.DeserializeObject<Dictionary<ulong, PlantBox>>(File.ReadAllText(FilePath));
            }
            else
            {
                _plantBoxes = new Dictionary<ulong, PlantBox>();
            }

            Console.WriteLine("Storage loaded");
        }

        public void Save()
        {
            Console.WriteLine("Saving storage...");

            File.WriteAllText(FilePath, JsonConvert.SerializeObject(_plantBoxes));

            Console.WriteLine("Storage saved");
        }

        public void ClearPlantBox(PlantBox plantBox)
        {
            if (plantBox != null)
            {
                plantBox.HistoricManager.Clear();
            }
        }

        public IEnumerator<PlantBox> GetEnumerator() => _plantBoxes.Values.GetEnumerator();

        IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
    }
}
