package com.lanyuanxiaoyao.service.command.commands.jobs;

import cn.hutool.core.lang.Snowflake;
import com.lanyuanxiaoyao.service.common.entity.FlinkJob;
import com.lanyuanxiaoyao.service.configuration.entity.info.TableMetaAdd;
import com.lanyuanxiaoyao.service.forest.service.InfoService;
import org.eclipse.collections.api.list.ImmutableList;

/**
 * @date 2022-06-29
 */
public abstract class AbstractAdder implements Adder {
    protected final ImmutableList<FlinkJob> flinkJobs;
    protected final InfoService infoService;
    protected final String database;
    protected final String type;
    protected final String schema;
    protected final String table;
    protected final String pulsarAddress;
    protected final String hdfs;

    protected final Snowflake snowflake = new Snowflake();

    public AbstractAdder(InfoService infoService, String database, String type, String schema, String table, String pulsarAddress, String hdfs) {
        this.infoService = infoService;
        this.flinkJobs = infoService.flinkJobList();

        this.database = database;
        this.type = type;
        this.schema = schema;
        this.table = table;
        this.pulsarAddress = pulsarAddress;
        this.hdfs = hdfs;
    }

    protected abstract ImmutableList<Job> getJobs();

    @Override
    public void execute() {
        for (Job j : getJobs()) {
            if (flinkJobs.noneSatisfy(job -> j.name.equals(job.getName()))) {
                infoService.saveFlinkJob(j.id, j.name, j.runMode);
            } else {
                if (j.isAppended) {
                    FlinkJob flinkJob = flinkJobs.select(job -> j.name.equals(job.getName())).getFirstOptional().orElseThrow(() -> new RuntimeException("Found duplicate flink job name"));
                    j.id = flinkJob.getId();
                } else {
                    throw new RuntimeException("Found duplicate flink job name");
                }
            }
            for (Table t : j.tables) {
                infoService.saveTableMeta(new TableMetaAdd(
                        t.id,
                        t.alias,
                        j.id,
                        t.hudiJobId,
                        t.syncYarnJobId,
                        t.compactionYarnJobId,
                        t.srcDb,
                        t.srcType,
                        t.srcSchema,
                        t.srcTable,
                        t.srcPulsarAddr,
                        t.srcTopic,
                        t.tgtDb,
                        t.tgtTable,
                        t.tgtHdfsPath,
                        t.filterField,
                        t.filterValues,
                        t.filterType,
                        t.bucketNumber
                ));
            }
        }
    }
}
