﻿namespace PoolCare.WithNancy.UnitTests
{
    using System;
    using System.IO;
    using System.Linq;
    using Nancy;

    public class TestRootPathProvider : IRootPathProvider
    {
        private static string cachedRootPath;

        public string GetRootPath()
        {
            if (!string.IsNullOrEmpty(cachedRootPath))
                return cachedRootPath;

            var currentDirectory = new DirectoryInfo(Environment.CurrentDirectory);

            var rootPathFound = false;

            while (!rootPathFound)
            {
                // ReSharper disable once PossibleNullReferenceException
                var directoriesContainingViewFolder = currentDirectory.GetDirectories(
                    "Views", SearchOption.AllDirectories);
                if (directoriesContainingViewFolder.Any())
                {
                    cachedRootPath = directoriesContainingViewFolder.First().FullName;
                    rootPathFound = true;
                }

                currentDirectory = currentDirectory.Parent;
            }

            return cachedRootPath;
        }
    }
}