package com.house365.tags;

import java.io.IOException;
import java.io.StringWriter;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;

import org.apache.commons.lang3.StringUtils;

/**
 * User: duhui
 * Date: 2015-01-17
 */
public class MagneticTag extends BodyTagSupport {

    /**
     */
    private static final long serialVersionUID = 1L;

    private String title;

    private String iconCls;

    private Integer number;

    private boolean displayNumber = true;

    private String cls;

    private String style;

    private String baseUrl;

    private boolean sortable = true;

    public void setStyle(String style) {
        this.style = style;
    }

    public void setCls(String cls) {
        this.cls = cls;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public void setIconCls(String iconCls) {
        this.iconCls = iconCls;
    }

    public void setNumber(Integer number) {
        this.number = number;
    }

    public void setDisplayNumber(boolean displayNumber) {
        this.displayNumber = displayNumber;
    }

    public void setBaseUrl(String baseUrl) {
        this.baseUrl = baseUrl;
    }

    public void setId(String id) {
        this.id = id;
    }

    public void setSortable(boolean sortable) {
        this.sortable = sortable;
    }

    @Override
    public int doEndTag() throws JspException {
        StringWriter bodyWriter = new StringWriter();
        try {
            if (this.getBodyContent() != null) {
                this.getBodyContent().writeOut(bodyWriter);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        StringBuilder builder = new StringBuilder();
        builder.append("<li class='tiles pointer " + iconCls + " " + StringUtils.trimToEmpty(cls) + " " + (sortable ? " sortable ui-sortable" : "") + "' style='" + StringUtils.trimToEmpty(style) + "'>");
        builder.append("<div onclick='window.location=\"" + StringUtils.trimToEmpty(baseUrl) + "\"'>");
        builder.append("<span class='content'>");
        builder.append(bodyWriter.toString());
        builder.append("</span>");
        if (displayNumber) {
            builder.append("<span class='tag'>");
            builder.append(number == null ? 0 : number);
            builder.append("</span>");
        }
        builder.append("<span class='tiles-name'>");
        builder.append(StringUtils.trimToEmpty(title));
        builder.append("</span>");
        builder.append("</div>");
        builder.append("</li>");

        try {
            pageContext.getOut().write(builder.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }

        return EVAL_BODY_INCLUDE;
    }
}
