package com.tmerclub.cloud.search.canal.support.parser;

import com.alibaba.fastjson2.JSON;
import com.tmerclub.cloud.search.canal.common.BinLogEventType;
import com.tmerclub.cloud.search.canal.common.OperationType;
import com.tmerclub.cloud.search.canal.model.CanalBinLogEvent;
import com.tmerclub.cloud.search.canal.model.CanalBinLogResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

/**
 * @author throwable
 * @version v1
 * @description
 * @since 2020/9/24 23:22
 */
public class DefaultCanalBinLogEventParser implements CanalBinLogEventParser {

    private static final Logger log = LoggerFactory.getLogger(DefaultCanalBinLogEventParser.class);

    @Override
    public <T> List<CanalBinLogResult<T>> parse(CanalBinLogEvent event,
                                                Class<T> klass,
                                                BasePrimaryKeyTupleFunction primaryKeyFunction,
                                                BaseCommonEntryFunction<T> commonEntryFunction) {
        BinLogEventType eventType = BinLogEventType.fromType(event.getType());
        if (BinLogEventType.UNKNOWN == eventType || BinLogEventType.QUERY == eventType) {
            if (log.isDebugEnabled()) {
                log.debug("监听到不需要处理或者未知的binlog事件类型[{}],将忽略解析过程返回空列表,binlog事件:{}", eventType, JSON.toJSONString(event));
            }
            return Collections.emptyList();
        }
        if (Boolean.TRUE.equals(event.getIsDdl())) {
            CanalBinLogResult<T> entry = new CanalBinLogResult<>();
            entry.setOperationType(OperationType.DDL);
            entry.setBinLogEventType(eventType);
            entry.setTableName(event.getTable());
            entry.setDatabaseName(event.getDatabase());
            entry.setSql(event.getSql());
            return Collections.singletonList(entry);
        }
        Optional.ofNullable(event.getPkNames()).filter(x -> x.size() == 1)
                .orElseThrow(() -> new IllegalArgumentException("DML类型binlog事件主键列数量不为1"));
        // 主键列的名称
        String primaryKeyName = event.getPkNames().get(0);
        List<Map<String, String>> data = event.getData();
        List<Map<String, String>> old = event.getOld();
        List<CanalBinLogResult<T>> entryList = new LinkedList<>();
        int dataSize = null != data ? data.size() : 0;
        int oldSize = null != old ? old.size() : 0;
        if (dataSize > 0) {
            for (int index = 0; index < dataSize; index++) {
                CanalBinLogResult<T> entry = new CanalBinLogResult<>();
                entryList.add(entry);
                entry.setSql(event.getSql());
                entry.setBinLogEventType(eventType);
                entry.setOperationType(OperationType.DML);
                entry.setDatabaseName(event.getDatabase());
                entry.setTableName(event.getTable());
                // 预防old节点空指针
                Map<String, String> oldItem = null;
                if (oldSize > 0 && index <= oldSize) {
                    oldItem = old.get(index);
                    entry.setBeforeData(commonEntryFunction.apply(oldItem));
                }
                Map<String, String> item = data.get(index);
                entry.setAfterData(commonEntryFunction.apply(item));
                // 封装主键
                entry.setPrimaryKey(primaryKeyFunction.apply(oldItem, item, primaryKeyName));
            }
        }
        return entryList;
    }
}
