
package com.tmerclub.cloud.search.listener;

import com.alibaba.fastjson2.JSON;
import com.tmerclub.cloud.common.i18n.I18nMessage;
import com.tmerclub.cloud.common.i18n.LanguageEnum;
import com.tmerclub.cloud.common.rocketmq.config.RocketMqConstant;
import com.tmerclub.cloud.search.canal.CanalGlue;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;

import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author tmerclub
 * @date 2021/02/03
 */
@Component
@RocketMQMessageListener(topic = RocketMqConstant.CANAL_TOPIC, consumerGroup = RocketMqConstant.CANAL_TOPIC)
public class BaseCanalListener implements RocketMQListener<String> {

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

    private static final Pattern PATTERN = Pattern.compile("\\w+[_]{1}[\\d]+");
    private static final String TABLE = "table";
    private static final String DATABASE = "database";

    @Autowired
    private CanalGlue canalGlue;

    @SuppressWarnings("unchecked")
    @Override
    public void onMessage(String message) {
        log.info("get mq message:{}", message);
        log.info("当前语言：{}, 语言编码：{}", I18nMessage.getLang(), LocaleContextHolder.getLocale());
        LocaleContextHolder.setLocale(new Locale(LanguageEnum.LANGUAGE_ZH_CN.getLanguage()));
        log.info("当前语言：{}, 语言编码：{}", I18nMessage.getLang(), LocaleContextHolder.getLocale());
        Map<String, String> map = JSON.parseObject(message, Map.class);
        map.put(TABLE, handleTableOrDatabaseName(map.get(TABLE)));
        map.put(DATABASE, handleTableOrDatabaseName(map.get(DATABASE)));
        canalGlue.process(JSON.toJSONString(map));
    }

    private String handleTableOrDatabaseName(Object o) {
        if (Objects.isNull(o)) {
            return null;
        }
        String name = o.toString();
        Matcher databaseMatcher = PATTERN.matcher(name);
        if (databaseMatcher.matches()) {
            name = name.substring(0, name.lastIndexOf('_'));
        }
        return name;
    }
}
