
package com.tmerclub.cloud.search.canal;

import cn.hutool.core.collection.CollectionUtil;
import com.tmerclub.cloud.search.canal.model.CanalBinLogEvent;
import com.tmerclub.cloud.search.canal.model.ModelTable;
import com.tmerclub.cloud.search.canal.support.adapter.SourceAdapterFacade;
import com.tmerclub.cloud.search.canal.support.processor.BaseCanalBinlogEventProcessor;
import com.tmerclub.cloud.search.canal.support.processor.CanalBinlogEventProcessorFactory;

import java.util.List;

/**
 * @author tmerclub
 */
public class LuckCanalGlue implements CanalGlue {

    private final CanalBinlogEventProcessorFactory canalBinlogEventProcessorFactory;

    @Override
    public void process(String content) {
        CanalBinLogEvent event = SourceAdapterFacade.X.adapt(CanalBinLogEvent.class, content);
        ModelTable modelTable = ModelTable.of(event.getDatabase(), event.getTable());
        List<BaseCanalBinlogEventProcessor<?>> baseCanalBinlogEventProcessors = this.canalBinlogEventProcessorFactory.get(modelTable);
        if (CollectionUtil.isEmpty(baseCanalBinlogEventProcessors)) {
            return;
        }
        baseCanalBinlogEventProcessors.forEach((processor) -> processor.process(event));
    }


    private LuckCanalGlue(CanalBinlogEventProcessorFactory canalBinlogEventProcessorFactory) {
        this.canalBinlogEventProcessorFactory = canalBinlogEventProcessorFactory;
    }

    public static LuckCanalGlue of(CanalBinlogEventProcessorFactory canalBinlogEventProcessorFactory) {
        return new LuckCanalGlue(canalBinlogEventProcessorFactory);
    }
}
