using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Blueprinter.Core
{
    public class BlueprintNodeWriter
    {
        private readonly string _path;
        private readonly ContentResolver _resolver;
        public BlueprintNodeWriter(string path, ContentResolver resolver)
        {
            _path = path;
            _resolver = resolver;
        }

        public async Task WriteAsync(BlueprintNode node)
        {
            await WriteAsync(_path, node);
        }

        private async Task WriteAsync(string path, BlueprintNode node)
        {
            path = string.Format(@"{0}/{1}", path, node.Name);

            if (node.Type == BlueprintNodeType.File)
            {
                await WriteFileAsync(path, node);
            }
            else
            {
                await WriteDirectoryAsync(path, node);
            }
        }

        private async Task WriteDirectoryAsync(string path, BlueprintNode node)
        {
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            foreach (var child in node.Children)
            {
                await WriteAsync(path, child);
            }
        }

        private async Task WriteFileAsync(string path, BlueprintNode node)
        {
            var shortcut = node.Shortcut;
            var content = await _resolver.FetchContentAsync(shortcut);

            using (var writer = new StreamWriter(path, false))
            {
                await writer.WriteAsync(content);
            }
        }
    }
}
