package cn.stylefeng.team.generator.core.tag;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.stylefeng.team.generator.api.TemplateGetApi;
import org.beetl.core.ByteWriter;
import org.beetl.core.Resource;
import org.beetl.core.Template;
import org.beetl.core.tag.Tag;

import java.util.Map;

@SuppressWarnings("all")
public class FormIncludeTag extends Tag {

    public static String RES_PREFIX = "templates/guns-v8-biz/frontend/";

    @Override
    public void render() {

        Object resourceId = getRelResourceId();

        TemplateGetApi bean = SpringUtil.getBean(TemplateGetApi.class);
        String templateContent = bean.getTemplateContentByResourceId(RES_PREFIX + String.valueOf(resourceId));

        Template template = gt.getTemplate(templateContent, ctx);

        Object config = this.ctx.globalVar.get("config");
        if (config != null) {
            template.binding("config", config);
        }


        if (this.args.length == 2) {

            Map<String, Object> tagParams = null;
            if (this.args[1] instanceof Map) {
                tagParams = (Map<String, Object>) this.args[1];
                template.binding(tagParams);
            } else {
                tagParams = BeanUtil.beanToMap(this.args[1], false, true);
                template.binding(tagParams);
            }

            template.binding("currentContextParams", tagParams);
        }

        ByteWriter bw = ctx.byteWriter;
        template.renderTo(bw);
    }

    protected Object getRelResourceId() {
        Resource sibling = ctx.getResource();

        return gt.getResourceLoader().getResourceId(sibling, (String) this.args[0]);
    }

}