/*
 * 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.seatunnel.connectors.seatunnel.preview.sink;

import lombok.SneakyThrows;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.seatunnel.api.common.SeaTunnelAPIErrorCode;
import org.apache.seatunnel.api.serialization.SerializationSchema;
import org.apache.seatunnel.api.table.type.SeaTunnelRow;
import org.apache.seatunnel.api.table.type.SeaTunnelRowType;
import org.apache.seatunnel.common.utils.JsonUtils;
import org.apache.seatunnel.connectors.seatunnel.common.sink.AbstractSinkWriter;
import org.apache.seatunnel.connectors.seatunnel.preview.config.PreviewParameters;
import org.apache.seatunnel.connectors.seatunnel.preview.config.RedisDataType;
import org.apache.seatunnel.connectors.seatunnel.preview.exception.PreviewConnectorException;
import org.apache.seatunnel.connectors.seatunnel.preview.util.HttpURLConnectionUtil;
import org.apache.seatunnel.connectors.seatunnel.preview.util.Singleton;
import org.apache.seatunnel.format.json.JsonSerializationSchema;
import org.apache.seatunnel.shade.com.fasterxml.jackson.core.JsonProcessingException;
import org.apache.seatunnel.shade.com.fasterxml.jackson.databind.JsonNode;
import org.apache.seatunnel.shade.com.fasterxml.jackson.databind.node.ArrayNode;
import redis.clients.jedis.Jedis;

import java.io.IOException;
import java.util.List;
import java.util.Objects;

public class PreviewSinkWriter extends AbstractSinkWriter<SeaTunnelRow, Void> {
    private final SeaTunnelRowType seaTunnelRowType;
    private final PreviewParameters previewParameters;
    private final SerializationSchema serializationSchema;
    private final Jedis jedis;

    public PreviewSinkWriter(SeaTunnelRowType seaTunnelRowType, PreviewParameters previewParameters) {
        this.seaTunnelRowType = seaTunnelRowType;
        this.previewParameters = previewParameters;
        // TODO according to format to initialize serializationSchema
        // Now temporary using json serializationSchema
        this.serializationSchema = new JsonSerializationSchema(seaTunnelRowType);
        this.jedis = previewParameters.buildJedis();
    }

    @SneakyThrows
    @Override
    public void write(SeaTunnelRow element) throws IOException {
        String data = new String(serializationSchema.serialize(element));
        RedisDataType redisDataType = previewParameters.getRedisDataType();
        String keyField = previewParameters.getKeyField();
        int max = previewParameters.getMax();
        String key = keyField;
        List<String> taskNum = RedisDataType.KEY.get(jedis, key + ":num");
        int num = CollectionUtils.isEmpty(taskNum) || StringUtils.isBlank(taskNum.get(0)) ? 0 : Integer.parseInt(taskNum.get(0));

        if (num > max) {
            if (previewParameters.getCanalMode() == 0) {
                throw new PreviewConnectorException(SeaTunnelAPIErrorCode.EXECUTE_MAX_TASK_NUM, "Execute to maximum number");
            }
            if (previewParameters.getCanalMode() == 1) {
                String flink = previewParameters.getFlink();
                String flinkJob = previewParameters.getFlinkJob();
                cancelJob(flink, flinkJob);
            }
        }
        redisDataType.set(jedis, key, data);
        Singleton.getSingleton().inc(key);

        RedisDataType.KEY.set(jedis, key + ":num", (num + 1) + "");

    }

    private void cancelJob(String flink, String flinkJob) throws JsonProcessingException {
        String overview = HttpURLConnectionUtil.doGet(flink + "/jobs/overview");
        JsonNode jsonNode = JsonUtils.stringToJsonNode(overview);
        JsonNode jobs = jsonNode.get("jobs");
        ArrayNode jsonNodes = JsonUtils.parseArray(jobs.toString());
        for (JsonNode node : jsonNodes) {
            String name = JsonUtils.findValue(node, "name");
            if (name.equals(flinkJob)) {
                String jid = JsonUtils.findValue(node, "jid");
                HttpURLConnectionUtil.doGet("http://localhost:8081/jobs/" + jid + "/yarn-cancel");
            }

        }
        ;
    }

    @Override
    public void close() throws IOException {
        if (Objects.nonNull(jedis)) {
            jedis.close();
        }
    }

}
