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 XmlContext : IContext
    {
        private readonly IRepository<BlueprintInfo> _blueprints;
        private readonly IRepository<TemplateInfo> _templates;

        public XmlContext(string path)
        {
            var blueprintsPath = string.Format(@"{0}/blueprints.xml", path);
            var templatesPath = string.Format(@"{0}/templates.xml", 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)
            {
                if (blueprint.Id == new Guid())
                {
                    _blueprints.Create(blueprint);
                }
                else
                {
                    _blueprints.Update(blueprint);
                }
            }
        }

        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);
                }
            }
        }
    }
}
