/**
 * Copyright Beijing Daheng Soft technology co. LTD
 * All right reserved.
 * 项目名称: 大恒泰山系统
 * 创建日期:2021/11/25
 */
package org.ts.ddcs.kafkaStream.source;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.processor.Processor;
import org.apache.kafka.streams.processor.ProcessorContext;
import org.apache.kafka.streams.processor.PunctuationType;
import org.apache.kafka.streams.state.KeyValueIterator;
import org.apache.kafka.streams.state.KeyValueStore;
import org.ts.ddcs.log.LogHelper;

import java.time.Duration;


/***
 * Date:2021/11/25
 * Title: 数据流处理器模块
 * Description：数据源
 * @author dylan
 * @version 1.0
 * Remark：认为有必要的其他信息
 */
@Slf4j
public class DataStreamSourceMapProcessor implements Processor<String, String> {

    private KeyValueStore<String, Integer> kvStore;

    @Override
    public void init(final ProcessorContext context) {
        context.schedule(Duration.ofMinutes(1), PunctuationType.STREAM_TIME, timestamp -> {

            //context.forward(new Record<>(entry.key, entry.value.toString(), timestamp));
            try (final KeyValueIterator<String, Integer> iter = kvStore.all()) {
                while (iter.hasNext()) {
                    final KeyValue<String, Integer> entry = iter.next();
                    log.info("topic {} count {}", entry.key, entry.value.toString());
                    kvStore.delete(entry.key);
                }
            }
        });
        kvStore = (KeyValueStore<String, Integer>) context.getStateStore("statusStoreCache");
    }

    @Override
    public void process(String s, String s2) {
        final Integer oldValue = kvStore.get(s);

        if (oldValue == null) {
            kvStore.put(s, 1);
        } else {
            kvStore.put(s, oldValue + 1);
        }
    }


    @Override
    public void close() {

    }
}
