using EPiServer.Framework;
using EPiServer.Framework.Initialization;
using EPiServer.ServiceLocation;
using System.Web.Mvc;
using System;
using EPiServer.ContentApi.Infrastructure;
using EPiServer.ContentApi.Search.Infrastructure;
using System.Web.Http;
using Newtonsoft.Json;
using EPiServer.ContentApi.Core.Infrastructure;
using EPiServer.Web;
using HeadlessWith101.Infrastructure.WebApi;

namespace HeadlessWith101.Infrastructure
{
    [InitializableModule]
    [ModuleDependency(typeof(ServiceContainerInitialization))]
    public class SiteInitialization : IConfigurableModule
    {
        public void ConfigureContainer(ServiceConfigurationContext context)
        {

            var contentApiOptions = new ContentApiOptions
            {
                MultiSiteFilteringEnabled = true,
                RequiredRole = "contentapiread",  // for Service API to access content 
                MinimumRoles = "contentapiread"   // to authorize access token per API request to get/search content (by default, no authorization) 
            };
            context.InitializeContentApi(contentApiOptions);
            context.InitializeContentSearchApi(new ContentSearchApiOptions()
            {
                SearchCacheDuration = TimeSpan.Zero
            });

            DependencyResolver.SetResolver(new StructureMapDependencyResolver(context.StructureMap()));
            GlobalConfiguration.Configure(config =>
            {
                config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.LocalOnly;
                config.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings();
                config.Formatters.XmlFormatter.UseXmlSerializer = true;
                config.DependencyResolver = new StructureMapResolver(context.StructureMap());
                config.MapHttpAttributeRoutes();
                config.EnableCors();
            });

        }

        public void Initialize(InitializationEngine context)
        {
            var options = ServiceLocator.Current.GetInstance<DisplayOptions>();
            AreaRegistration.RegisterAllAreas();
        }

        public void Uninitialize(InitializationEngine context) { }
    }
}