package cc.smtweb.system.canal.file.common;

import cc.smtweb.framework.core.common.SwEnum;
import cc.smtweb.framework.core.db.DbEngine;
import cc.smtweb.framework.core.exception.SwException;
import cc.smtweb.framework.core.util.CommUtil;
import cc.smtweb.framework.core.util.FileUtil;
import cc.smtweb.framework.core.util.JsonUtil;
import cc.smtweb.system.canal.file.impl.DmSqlFileWork;
import cc.smtweb.system.canal.file.impl.KbSqlFileWork;
import cc.smtweb.system.canal.file.impl.MySqlFileWork;
import cc.smtweb.system.canal.file.impl.OracleFileWork;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author yaoq
 * @Date 2022年09月20日 9:26
 * @Description
 */
public class FileDecodeFactory {

    private volatile static FileDecodeFactory instance = null;

    public static FileDecodeFactory getInstance() {
        if (instance == null) {
            synchronized (FileDecodeFactory.class) {
                if (instance == null) instance = new FileDecodeFactory();
            }
        }
        return instance;
    }

    private Map<String, Class<? extends AbstractFileWork>> mapWorks;
    private Map<String, FieldMappingVo> mapMapping;


    private FileDecodeFactory() {
        mapWorks = new HashMap<>();
        mapWorks.put(SwEnum.DbType.DMSQL.value.toLowerCase(), DmSqlFileWork.class);
        mapWorks.put(SwEnum.DbType.KBSQL.value.toLowerCase(), KbSqlFileWork.class);
        mapWorks.put(SwEnum.DbType.MYSQL.value.toLowerCase(), MySqlFileWork.class);
        mapWorks.put(SwEnum.DbType.ORACLE.value.toLowerCase(), OracleFileWork.class);

        mapMapping = new HashMap<>();
        buildFieldMapping();
    }

    public AbstractFileWork getFileWork(String key) throws Exception {
        Class<? extends AbstractFileWork> cls = mapWorks.get(key.toLowerCase());
        if (cls == null) throw new SwException("暂不支持[" + key + "]类型数据库文件解析！");
        return cls.newInstance();
    }

    private void buildFieldMapping() {
        String path = Thread.currentThread().getContextClassLoader().getResource("").getPath() + "config/field-mapping.json";
        List<FieldMappingVo> list = JsonUtil.parseList(FileUtil.readFileStr(path), FieldMappingVo.class);
        if (CommUtil.isEmpty(list)) return;
        for (FieldMappingVo bean : list) {
            mapMapping.put(bean.getType(), bean);
        }
    }

    public FieldMappingVo getFieldMapping() {
        return mapMapping.get(DbEngine.getInstance().getDbType());
    }
}
