﻿using System;
using System.Web.Mvc;
using System.Collections.Generic;
using RalphsDotNet.Apps.Studio.Interface;
using System.Web.Routing;
using System.Web.Configuration;
using System.Web.Hosting;

namespace RalphsDotNet.Apps.Studio
{
    public class StudioViewEngine : RazorViewEngine
    {
        public StudioViewEngine () : base ()
        {
            var paths = new List<string> ();
            paths.Add ("~/Views/{1}/{0}.cshtml");
            paths.Add ("~/Views/Shared/{1}/{0}.cshtml");

            foreach (var extension in ApplicationProvider.Application.ExtensionInfos) {
                paths.Add ("~/Views/" + extension.Id + "/{1}/{0}.cshtml");
                paths.Add ("~/Views/" + extension.Id + "/Shared/{1}/{0}.cshtml");
            }

            ViewLocationFormats = paths.ToArray ();
            MasterLocationFormats = paths.ToArray ();
        }

        protected override bool FileExists (ControllerContext controllerContext, string virtualPath)
        {
            var r = base.FileExists (controllerContext, virtualPath);
            if (r && controllerContext.RouteData.Route as Route != null) {
                var routeParts = ((Route)controllerContext.RouteData.Route).Url.Split ('/');
                var pathParts = virtualPath.Split ('/');
                if (routeParts.Length > 0 && pathParts.Length > 0 && routeParts [0] != "{controller}" && routeParts [0] != pathParts [2]) {
                    r = false;
                }
            }

            return r;
        }
    }
}

