/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.paimon.benchmark;

import org.apache.paimon.benchmark.utils.BenchmarkUtils;

import org.apache.commons.io.FilenameUtils;
import org.apache.flink.util.FileUtils;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/** Benchmark sink. */
public class Sink {

    private final String name;
    private final String beforeSql;
    private final String tableName;
    private final String tableProperties;

    private Sink(String name, String beforeSql, String tableName, String tableProperties) {
        this.name = name;
        this.beforeSql = beforeSql == null ? "" : beforeSql;
        this.tableName = tableName;
        this.tableProperties = tableProperties;
    }

    public String name() {
        return name;
    }

    public String beforeSql() {
        return beforeSql;
    }

    public String tableName() {
        return tableName;
    }

    public String tableProperties() {
        return tableProperties;
    }

    public static List<Sink> load(Path location) throws IOException {
        Path sinkLocation = location.resolve("sinks");

        List<Sink> result = new ArrayList<>();
        Iterator<Path> it = Files.list(sinkLocation).iterator();
        while (it.hasNext()) {
            Path p = it.next();
            Map<?, ?> yaml =
                    BenchmarkUtils.YAML_MAPPER.readValue(
                            FileUtils.readFileUtf8(p.toFile()), Map.class);
            result.add(
                    new Sink(
                            FilenameUtils.removeExtension(p.getFileName().toString()),
                            (String) yaml.get("before"),
                            (String) yaml.get("sink-name"),
                            (String) yaml.get("sink-properties")));
        }
        return result;
    }
}
