using System.IO;
using System.Collections.Generic;
using Microsoft.Dnx.Compilation;
using Microsoft.Dnx.Compilation.CSharp;

namespace C1.Web.Mvc.Compiler.Preprocess
{
    /// <summary>
    /// This class is for:
    /// Embedded controller source code into the assembly.
    /// </summary>
    public class ControllerSourcesCompilation : ICompileModule
    {
        private const string ControllerSourcePattern = "*.cs";

        public void BeforeCompile(BeforeCompileContext context)
        {
            var projectFolder = context.ProjectContext.ProjectDirectory;
            var controllerSources = GetControllerSources(projectFolder, "Controllers");
            foreach (var controllerSource in controllerSources)
            {
                context.Resources.Add(controllerSource);
            }
        }

        private static IList<ResourceDescriptor> GetControllerSources(string projectFolder, string folderName)
        {
            var controllerSources = new List<ResourceDescriptor>();
            var path = Path.Combine(projectFolder, folderName);
            foreach(var file in Directory.GetFiles(path, ControllerSourcePattern))
            {
                var fileName = Path.GetFileName(file);
                var sourceName = Path.Combine(folderName, fileName).Replace('\\', '/');
                controllerSources.Add(new ResourceDescriptor
                {
                    FileName = fileName,
                    Name = sourceName,
                    StreamFactory = () => File.OpenRead(file)
                });
            }

            foreach (var subFolder in Directory.GetDirectories(path))
            {
                var subFolderName = Path.GetFileName(subFolder);
                var sourceName = Path.Combine(folderName, subFolderName);
                var subFolderControllerSources = GetControllerSources(projectFolder, sourceName);
                controllerSources.AddRange(subFolderControllerSources);
            }

            return controllerSources;
        }

        public void AfterCompile(AfterCompileContext context)
        {
        }
    }
}