/**
 * Copyright 2019 DH
 * All right reserved.
 * 项目名称: 大恒泰山系统
 * 创建日期:2021/12/16
 */
package org.ts.ddcs.dataStream;


import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/***
 * Date:2021/12/16
 * Title:数据匹配器模块
 * Description：每个适配器处理器
 * @author dylan
 * @mender：（文件的修改者，文件创建者之外的人）
 * @version 1.0
 * Remark：认为有必要的其他信息
 */
@Slf4j
public abstract class DataStreamProcessor {
    private String processorName;
    private String templateName;
    private DataStreamProcessor preProcessor;
    private DataStreamProcessor nextProcessor;
    protected DataStreamLineManager context;
    private boolean isNext = false;

    public abstract void init(DataStreamLineManager context);

    public abstract void process(DataStreamAdapter dataStreamAdapter) throws UnsupportedEncodingException, ParseException;

    public abstract void close(DataStreamAdapter dataStreamAdapter);

    public abstract void batchComplete(DataStreamAdapter dataStreamAdapter) throws ParseException;

    public abstract List<Map<String,Object>> sink(DataStreamAdapter dataStreamAdapter);

    public void setPreProcessor(DataStreamProcessor processor) {
        this.preProcessor = processor;
    }

    public void setNextProcessor(DataStreamProcessor processor) {
        this.nextProcessor = processor;
    }

    public DataStreamProcessor getPreProcessor() {
        return this.preProcessor;
    }

    public DataStreamProcessor getNextProcessor() {
        return this.nextProcessor;
    }

    public void setProcessorName(String processorName) {
        this.processorName = processorName;
    }

    public void setTemplateName(String templateName) {
        this.templateName = templateName;
    }

    public void next(boolean isNext) {
        this.isNext = isNext;
    }

    public void stream(DataStreamAdapter dataStreamAdapter) throws UnsupportedEncodingException, ParseException {
        try {
            this.isNext = false;
            log.info("processor {}",this.getClass().getName());
            this.process(dataStreamAdapter);
            if (this.isNext) {
                if (null != nextProcessor) {
                    nextProcessor.stream(dataStreamAdapter);
                }
            } else {
                this.backStream(dataStreamAdapter);
            }
        }catch (Exception e){
            throw  e;
        }
    }

    private void backStream(DataStreamAdapter dataStreamAdapter) {
        try {
            this.close(dataStreamAdapter);
            if (null != preProcessor) {
                preProcessor.backStream(dataStreamAdapter);
            }
        }catch (Exception e){
            throw  e;
        }
    }

}
