using Blueprinter.Core.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Blueprinter.Core.Services
{
    public class JsonContext : IContext
    {
        private readonly IRepository<BlueprintInfo> _blueprints;
        private readonly IRepository<TemplateInfo> _templates;

        public JsonContext(string path)
        {
            var blueprintsPath = string.Format(@"{0}/blueprints.json", path);
            var templatesPath = string.Format(@"{0}/templates.json", path);

            _blueprints = new BlueprintInfoRepository(blueprintsPath);
            _templates = new TemplateInfoRepository(templatesPath);

        }

        public IEnumerable<BlueprintInfo> GetAllBlueprints()
        {
            return _blueprints.All();
        }


        public void SaveBlueprints(IEnumerable<BlueprintInfo> blueprints)
        {
            _blueprints.Delete(b => !blueprints.Select(bp => bp.Id).Contains(b.Id));

            foreach (var blueprint in blueprints)
            {
                SaveBlueprint(blueprint);
            }

            OnBlueprintsUpdated();
        }

        public IEnumerable<TemplateInfo> GetAllTemplates()
        {
            return _templates.All();
        }

        public void SaveTemplates(IEnumerable<TemplateInfo> templates)
        {
            _templates.Delete(t => !templates.Select(tmps => tmps.Id).Contains(t.Id));

            foreach (var template in templates)
            {
                if (template.Id == new Guid())
                {
                    _templates.Create(template);
                }
                else
                {
                    _templates.Update(template);
                }
            }
        }

        protected void OnBlueprintsUpdated()
        {
            if (BlueprintsUpdated != null)
            {
                BlueprintsUpdated(this, EventArgs.Empty);
            }
        }

        public event EventHandler BlueprintsUpdated;


        public void SaveBlueprint(BlueprintInfo bp)
        {
            if (bp.Id == new Guid())
            {
                _blueprints.Create(bp);
            }
            else
            {
                _blueprints.Update(bp);
            }
        }
    }
}
