package me.chyxion.tigon.webmvc;

import lombok.Getter;
import lombok.Setter;
import org.slf4j.Logger;
import java.util.Locale;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.web.servlet.View;
import me.chyxion.tigon.webmvc.util.ResponseTool;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author Shaun Chyxion <br>
 * chyxion@163.com <br>
 * Mar 19, 2017 11:23:01
 */
public class DefaultViewResolver implements ViewResolver, Ordered {
    private static final Logger log = 
        LoggerFactory.getLogger(DefaultViewResolver.class);

    @Autowired
    private JSONViewConfig jsonViewConfig;

    /**
     * view resolver order
     */
    @Getter
    @Setter
    private int order;

    /**
     * {@inheritDoc}
     */
    @Override
    public View resolveViewName(String rawViewName, Locale locale) throws Exception {
        log.debug("Base view resolver resolve view name [{}].", rawViewName);
        // parse view name
        View view = null;
        if (rawViewName.startsWith(ResponseTool.PREFIX_DATA)) {
            String viewName = rawViewName.substring(ResponseTool.PREFIX_DATA.length());
            log.debug("Resolve view name [{}] As JSON data.", viewName);
            view = new JSONView(new JSONViewDataModel(viewName), jsonViewConfig);
        }

        if (view == null) {
            log.debug("No view type found, render as JSON view [{}].", rawViewName);
            view = new JSONView(rawViewName, jsonViewConfig);
        }
        return view;
    }
}
