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

namespace Blueprinter.Core
{
    public class ContentResolver
    {
        private readonly IRepository<TemplateInfo> _repository;
        public ContentResolver(IRepository<TemplateInfo> templateRepository)
        {
            _repository = templateRepository;
        }

        public async Task<string> FetchContentAsync(string shortcut)
        {
            var template = _repository.Find(t =>
                t.Shortcut.Equals(shortcut, StringComparison.InvariantCultureIgnoreCase));

            if (template == null)
            {
                return null;
            }

            var content = template.Content;

            return template.Type == TemplateType.Text ? content : await FetchUrlAsync(content);
        }

        private async Task<string> FetchUrlAsync(string url)
        {
            using (var client = new WebClient())
            {
                return await client.DownloadStringTaskAsync(url);
            }
        }
    }
}
