package org.springblade.flow.engine.custom.variables.type;


import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.SerializerFeature;

import org.flowable.variable.api.types.ValueFields;
import org.flowable.variable.api.types.VariableType;
import org.springblade.flow.engine.custom.variables.entity.FormDataInfo;
import org.springframework.stereotype.Component;

/**
 * @author LoveMyOrange
 * @create 2022-01-13 16:50
 */
@Component
public class JsonVariableType implements VariableType {
    @Override
    public String getTypeName() {
        return "formDataJson";
    }

    @Override
    public boolean isCachable() {
        return true;
    }

    @Override
    public boolean isAbleToStore(Object value) {
        if(value==null){
            return false;
        }
        return FormDataInfo.class.isAssignableFrom(value.getClass());
    }

    @Override
    public void setValue(Object value, ValueFields valueFields) {
            if(null==value){
                valueFields.setBytes(null);
            }
            else{
                try{
                    valueFields.setBytes(StrUtil.bytes(JSON.toJSONString(value, SerializerFeature.WriteMapNullValue)));
                }
                catch (Exception e){
                    e.printStackTrace();
                }
            }
    }

    @Override
    public Object getValue(ValueFields valueFields) {
        try {
            byte[] bytes = valueFields.getBytes();
            String str = StrUtil.str(bytes, "UTF-8");
            return JSONObject.parseObject(str,new TypeReference<FormDataInfo>(){});
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}
