package com.cool.bang.core.freemarker;

import freemarker.template.*;

/**
 *  Freemarker Base Directive (freemarker 自定义转换基础类)
 *
 *  @author GuoPeiZhi
 *  2020-6-30 9:10
 */
public class BaseDirective {


    /**
     * String 转换
     */
    public String getString(TemplateModel paramValue) throws TemplateModelException {

        if (paramValue == null) {
            return "";
        }
        // 字符串
        if (paramValue instanceof TemplateScalarModel) {
            return ((TemplateScalarModel) paramValue).getAsString();
        }else{
            throw new TemplateModelException("String转换异常!");
        }
    }

    /**
     * long 转换
     */
    public long getLong(TemplateModel paramValue) throws TemplateModelException {

        if (paramValue == null) {
            return 0;
        }
        if (paramValue instanceof TemplateScalarModel) { // 字符串
            String value = ((TemplateScalarModel)paramValue).getAsString();
            return Long.parseLong(value);
        } else if (paramValue instanceof TemplateNumberModel) { // 数字
            return ((TemplateNumberModel)paramValue).getAsNumber().longValue();
        } else {
            throw new TemplateModelException("Long转换异常!");
        }
    }

    /**
     * int 转换
     */
    public int getInt(TemplateModel paramValue) throws TemplateModelException {

        if (paramValue == null) {
            return 0;
        }
        if (paramValue instanceof TemplateScalarModel) {
            return Integer.parseInt(((TemplateScalarModel)paramValue).getAsString());
        } else if (paramValue instanceof TemplateNumberModel) {
            return ((TemplateNumberModel)paramValue).getAsNumber().intValue();
        } else {
            throw new TemplateModelException("int转换异常!");
        }

    }

    /**
     *  boolean 转换
     */
    public boolean getBoolean(TemplateModel paramValue) throws TemplateModelException {

        if(paramValue == null) {
            return false;
        }
        if (paramValue instanceof TemplateScalarModel) {
            return Boolean.parseBoolean(((TemplateScalarModel)paramValue).getAsString());
        } else if (paramValue instanceof TemplateBooleanModel) {
            return ((TemplateBooleanModel)paramValue).getAsBoolean();
        } else {
            throw new TemplateModelException("boolean转换异常!");
        }
    }
}
