package com.wisedu.coeus.core.tag;

import com.wisedu.coeus.core.ConstantStatic;
import com.wisedu.coeus.core.bo.LoginUser;
import com.wisedu.coeus.debug.Logger;
import com.wisedu.coeus.debug.LoggerFactory;
import com.wisedu.coeus.helper.ApplicationHelper;
import com.wisedu.coeus.util.Strings;
import com.wisedu.coeus.web.AppConfig;
import com.wisedu.coeus.web.LoginContext;

import javax.servlet.ServletContext;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
import java.io.IOException;
import java.util.Locale;

/**
 * 静态资源重定向基类
 */
public abstract class StaticResourceTag extends TagSupport {

    /* 静态资源的URL */
    protected String resourceUrl;

    /* 自动启用locale */
    protected boolean autoLocale;

    @Override
    public int doEndTag() throws JspException {
        final String content = getOutputHtml();
        if (Strings.isNotEmpty(content)) {
            try {
                pageContext.getOut().write(content);
            } catch (IOException e) {
                throw new JspException(e);
            }
        }

        return EVAL_PAGE;
    }

    /**
     * 根据URL获取标签对应的输出
     * @return
     */
    protected abstract String getOutputHtml();

    protected abstract String getBaseUrl();

    public String getResourceUrl() {
        this.resourceUrl = Strings.trimToEmpty(this.resourceUrl);

        if (this.resourceUrl.indexOf("://") > 0) {
            return this.resourceUrl;
        }

        final StringBuilder sbHref = new StringBuilder(256);
        String host = getBaseUrl();

        if (Strings.isEmpty(host)) {
            host = ApplicationHelper.getContextPath();
        }

        // 去掉结尾的/
        if (host.endsWith("/")) {
            host = host.substring(0, host.length() - 1);
        }

        sbHref.append(host);

        if (autoLocale) {
            LoginUser loginUser = LoginContext.getLoginUser();
            Locale locale = null;
            if (loginUser != null && loginUser.getUserLocale() != null) {
                locale = loginUser.getUserLocale();
            }
            else {
                locale = pageContext.getRequest().getLocale();
            }
            if (! locale.equals(ConstantStatic.DEFAULT_LOCALE)) {
                // 区域不是默认区域，进行url拼接
                sbHref.append("/").append(locale.toString());
            }
        }

        // 地址开头不是/，拼接/
        if (! resourceUrl.startsWith("/")) {
            sbHref.append("/");
        }
        sbHref.append(resourceUrl);

        return sbHref.toString();
    }
}
