package com.jsc.dsp.service;

import com.alibaba.fastjson.JSON;
import com.jsc.dsp.utils.ApplicationContextProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;

import java.util.ArrayList;
import java.util.Base64.Encoder;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public abstract class StreamService {
    @Autowired
    Encoder base64EnCoder;

    @Autowired
    private Environment environment;

    protected ExecutorService executorService = Executors.newCachedThreadPool();

    //向对应的topic发送消息
    public abstract void sendMessage(byte[] msg);

    //接受对应topic的消息，并对数据进行做业务上的处理
    public abstract void receiveMessage(Object payload);

    protected void sendToNext(Map<String, Object> data) {
        ArrayList<String> queue = null;
        if (data.get("processQueue") != null) {
            queue = (ArrayList<String>) data.get("processQueue");
        }
        if (queue.size() > 0) {
            queue.remove(0);
        }
        if (queue.size() > 0) {
            String className = environment.getProperty("topics." + queue.get(0));
            data.put("processQueue", queue);
            executorService.execute(() -> {
                try {
                    StreamService service;
                    service = (StreamService) ApplicationContextProvider.getBean(Class.forName(className));
                    service.sendMessage(base64EnCoder.encode(JSON.toJSONBytes(data)));
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            });
        }
    }
}
