package me.chyxion.tigon.jsp;

import java.util.Locale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletContext;
import java.net.MalformedURLException;
import org.springframework.web.servlet.View;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

/**
 * @version 0.0.1
 * @since 0.0.1
 * @author Shaun Chyxion <br>
 * chyxion@163.com <br>
 * Dec 5, 2014 2:33:18 PM
 */
public class InternalResourceViewResolverExt 
	extends InternalResourceViewResolver {
	private static final Logger log = 
		LoggerFactory.getLogger(InternalResourceViewResolverExt.class);

    @Autowired
    private ServletContext sc;

    /**
     * {@inheritDoc}
     */
    @Override
    public View resolveViewName(String viewName, Locale locale) 
    		throws Exception {
    	return super.resolveViewName(viewName(viewName), locale);
    }
    
    /**
     * {@inheritDoc}
     */
	@Override
	protected boolean canHandle(String viewName, Locale locale) {
		try {
			// avoid 404
			return sc.getResource(getPrefix() + viewName(viewName) + getSuffix()) != null;
		}
		catch (MalformedURLException e) {
			log.warn("InternalResourceViewResolverExt#canHandle Eorror Caused.", e);
			return false;
		}
	}

	/**
	 * Process View Name
	 * @param name raw name
	 * @return jsp file name
	 */
	private String viewName(String name) {
    	return name.replaceAll("(?i)(^\\s*jsp\\:)|(\\.jsp\\s*$)", "");
	}
}
