package com.wisedu.coeus.core.tag;

import com.wisedu.coeus.helper.ApplicationHelper;
import com.wisedu.coeus.util.Strings;
import com.wisedu.coeus.web.AppConfig;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by 01112026 on 14-8-4.
 */
public class URLTag extends TagSupport {
    private String code;

    // 参数列表，“,”号分隔
    private String params;

    public void setCode(final String code) {
        this.code = code;
    }

    public void setParams(final String params) {
        this.params = params;
    }


    @Override
    @SuppressWarnings("unchecked")
    public int doEndTag() throws JspException {

        StringBuilder sbHtml = new StringBuilder(1024);

        String[] paramStrArr = null;
        String URL = AppConfig.getProperty(code);
        sbHtml.append(ApplicationHelper.getContextPath());
        if (Strings.isNotEmpty(params)&&Strings.isNotEmpty(URL)) {
            paramStrArr = params.split(",");

            for (int i = 0; i < paramStrArr.length; i++) {
                Pattern pattern = Pattern.compile("\\{" + i + "\\}");
                Matcher matcher = pattern.matcher(URL);
                if (matcher.find() && Strings.isNotEmpty(paramStrArr[i])) {
                    URL = matcher.replaceAll(paramStrArr[i]);
                } else {
                    continue;
                }
            }
        }
        sbHtml.append(URL);
        try {
            pageContext.getOut().write(sbHtml.toString());
        } catch (IOException e) {

        }
        return EVAL_PAGE;
    }
}
