package com.huigou.bpm.management.translate.bpmn;

import com.huigou.bpm.management.domain.model.ChartKind;
import com.huigou.bpm.management.domain.model.ProcessDefinition;
import com.huigou.bpm.management.translate.ActivitiXmlTranslator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

/**
 * 将平台的BPMN流程图xml转换成activiti的流程图xml。
 *
 * @author yonghuan
 */
public class BpmnActivitiXmlTranslator implements ActivitiXmlTranslator {

    private final static Logger LOG = LoggerFactory.getLogger(BpmnActivitiXmlTranslator.class);
    private String procInstExecutionListenerBeanName;
    private String bizTaskExecutionListenerBeanName;
    private String serviceExecutorBeanName;


    public void setProcInstExecutionListenerBeanName(String procInstExecutionListenerBeanName) {
        this.procInstExecutionListenerBeanName = procInstExecutionListenerBeanName;
    }

    public void setBizTaskExecutionListenerBeanName(String bizTaskExecutionListenerBeanName) {
        this.bizTaskExecutionListenerBeanName = bizTaskExecutionListenerBeanName;
    }

    public void setServiceExecutorBeanName(String serviceExecutorBeanName) {
        this.serviceExecutorBeanName = serviceExecutorBeanName;
    }

    @Override
    public boolean supports(ProcessDefinition definition) {
        return ChartKind.BPMN2.id.equals(definition.getChartKindId());
    }

    @Override
    public InputStream translate(ProcessDefinition definition) {
        Assert.hasText(definition.getXml(), "流程xml不能为空");
        byte[] activitiDefinitionsXml = new MxGraphXmlParser(definition, procInstExecutionListenerBeanName, bizTaskExecutionListenerBeanName, serviceExecutorBeanName).parse();
        if (LOG.isInfoEnabled()) {
            String xml = new String(activitiDefinitionsXml, StandardCharsets.UTF_8);
            LOG.info(xml);
        }
        return new ByteArrayInputStream(activitiDefinitionsXml);
    }
}
