/*
 * #%L
 * fujion
 * %%
 * Copyright (C) 2008 - 2016 Regenstrief Institute, Inc.
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * #L%
 */
package org.fujion.servlet;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.fujion.annotation.ComponentScanner;
import org.fujion.annotation.EventTypeScanner;
import org.fujion.component.BaseComponent;
import org.fujion.event.Event;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceChainRegistration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.resource.AppCacheManifestTransformer;
import org.springframework.web.servlet.resource.GzipResourceResolver;
import org.springframework.web.servlet.resource.ResourceResolver;
import org.springframework.web.servlet.resource.VersionResourceResolver;

@EnableWebMvc
@Configuration
public class ServletConfiguration extends WebMvcConfigurerAdapter implements ApplicationContextAware {
    
    private static final Log log = LogFactory.getLog(ServletConfiguration.class);

    private final GzipResourceResolver gzipResourceResolver = new GzipResourceResolver();

    private final ResourceResolver contentVersionResolver = new VersionResourceResolver().addContentVersionStrategy("/**");

    private final ResourceResolver webjarResourceResolver = new WebJarResourceResolver();

    private final FujionResourceTransformer fujionResourceTransformer = new FujionResourceTransformer();

    private final AppCacheManifestTransformer appCacheManifestTransformer = new AppCacheManifestTransformer();

    private final MinifiedResourceResolver minifiedResourceResolver = new MinifiedResourceResolver("js", "css");

    private ApplicationContext applicationContext;

    public ServletConfiguration() {
        ComponentScanner.getInstance().scanPackage(BaseComponent.class.getPackage());
        EventTypeScanner.getInstance().scanPackage(Event.class.getPackage());
    }

    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer.mediaType("fsp", MediaType.TEXT_HTML);
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        addResourceHandlers(registry, "/webjars/**", "classpath:/META-INF/resources/webjars/", webjarResourceResolver);
        addResourceHandlers(registry, "/web/**", "classpath:/web/", null);
        addResourceHandlers(registry, "/**", "/", contentVersionResolver);
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        try {
            Resource[] resources = applicationContext.getResources("/index.*");

            if (resources.length > 0) {
                if (resources.length > 1) {
                    log.warn("Multiple home page candidates detected - only one will be selected.");
                }

                String file = "/" + resources[0].getFilename();
                registry.addViewController("/").setViewName(file);
                log.info("Default home page set to: " + file);
            } else {
                log.info("No default home page detected.");
            }
        } catch (Exception e) {
            log.error("Error while attempting to detect default home page.", e);
        }
    }

    private void addResourceHandlers(ResourceHandlerRegistry registry, String pattern, String locations,
                                     ResourceResolver customResourceResolver) {
        //@formatter:off
        ResourceChainRegistration chain = registry
            .addResourceHandler(pattern)
            .addResourceLocations(locations)
            .resourceChain(false);

        if (customResourceResolver != null) {
            chain.addResolver(customResourceResolver);
        }

        chain
            .addResolver(minifiedResourceResolver)
            .addResolver(gzipResourceResolver)
            .addTransformer(fujionResourceTransformer)
            .addTransformer(appCacheManifestTransformer);
        //@formatter:on
    }
    
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;

    }
    
}

@@ -2153,20 +2153,16 @@
 Aware %7B%0A
-    
 %0A    pri
@@ -2236,16 +2236,20 @@
 class);%0A
+    
 %0A    pri
@@ -2323,32 +2323,36 @@
 urceResolver();%0A
+    
 %0A    private fin
@@ -2456,24 +2456,28 @@
 egy(%22/**%22);%0A
+    
 %0A    private
@@ -2551,24 +2551,28 @@
 Resolver();%0A
+    
 %0A    private
@@ -2657,32 +2657,36 @@
 eTransformer();%0A
+    
 %0A    private fin
@@ -2781,16 +2781,20 @@
 rmer();%0A
+    
 %0A    pri
@@ -2895,24 +2895,28 @@
 s%22, %22css%22);%0A
+    
 %0A    private
@@ -2951,24 +2951,28 @@
 ionContext;%0A
+    
 %0A    public 
@@ -3158,32 +3158,36 @@
 ckage());%0A    %7D%0A
+    
 %0A    @Override%0A 
@@ -3328,32 +3328,36 @@
 XT_HTML);%0A    %7D%0A
+    
 %0A    @Override%0A 
@@ -3699,24 +3699,28 @@
 ver);%0A    %7D%0A
+    
 %0A    @Overri
@@ -3886,16 +3886,28 @@
 ex.*%22);%0A
+            
 %0A       
@@ -4094,32 +4094,48 @@
               %7D%0A
+                
 %0A               
@@ -4211,16 +4211,24 @@
 stry.add
+Redirect
 ViewCont
@@ -4241,22 +4241,10 @@
 (%22/%22
-).setViewName(
+, 
 file
@@ -4529,24 +4529,28 @@
     %7D%0A    %7D%0A
+    
 %0A    private
@@ -5284,28 +5284,24 @@
 er:on%0A    %7D%0A
-    
 %0A    @Overri
@@ -5458,22 +5458,26 @@
 ontext;%0A
+        
 %0A    %7D%0A
-    
 %0A%7D%0A

Use redirect view controller for default home page.