/*
 * 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.datasource.plugin.rabbitmq;

import org.apache.commons.lang3.StringUtils;

import com.rabbitmq.client.*;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.URISyntaxException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.TimeoutException;

import static org.apache.seatunnel.datasource.plugin.rabbitmq.RabbitmqConnectorErrorCode.*;

@Slf4j
@Data
public class RabbitmqClientService {
    private RabbitConfiguration config;
    private ConnectionFactory connectionFactory;
    private Connection connection;
    private Channel channel;

    public RabbitmqClientService(RabbitConfiguration config) {
        try {
            getConnectionFactory(config);
            connectionFactory.newConnection();
            connection.createChannel();
            // set channel prefetch count
            if (config.getPrefetchCount() != null) {
                channel.basicQos(config.getPrefetchCount(), true);
            }
            setupQueue();
        } catch (Exception e) {
            throw new RabbitmqConnectorException(
                    CREATE_RABBITMQ_CLIENT_FAILED,
                    String.format(
                            "Error while create RMQ client with %s at %s",
                            config.getQueueName(), config.getHost()),
                    e);
        }
    }

    public static Connection getConnectionFactory(RabbitConfiguration config) {
        ConnectionFactory factory = new ConnectionFactory();
        if (!StringUtils.isEmpty(config.getUri())) {
            try {
                factory.setUri(config.getUri());
            } catch (URISyntaxException e) {
                throw new RabbitmqConnectorException(PARSE_URI_FAILED, e);
            } catch (KeyManagementException e) {
                // this should never happen
                throw new RabbitmqConnectorException(INIT_SSL_CONTEXT_FAILED, e);
            } catch (NoSuchAlgorithmException e) {
                // this should never happen
                throw new RabbitmqConnectorException(SETUP_SSL_FACTORY_FAILED, e);
            }
        } else {
            factory.setHost(config.getHost());
            factory.setPort(config.getPort());
            factory.setVirtualHost(config.getVirtualHost());
            factory.setUsername(config.getUsername());
            factory.setPassword(config.getPassword());
        }

        if (config.getAutomaticRecovery() != null) {
            factory.setAutomaticRecoveryEnabled(config.getAutomaticRecovery());
        }
        if (config.getConnectionTimeout() != null) {
            factory.setConnectionTimeout(config.getConnectionTimeout());
        }
        if (config.getNetworkRecoveryInterval() != null) {
            factory.setNetworkRecoveryInterval(config.getNetworkRecoveryInterval());
        }
        if (config.getRequestedHeartbeat() != null) {
            factory.setRequestedHeartbeat(config.getRequestedHeartbeat());
        }
        if (config.getTopologyRecovery() != null) {
            factory.setTopologyRecoveryEnabled(config.getTopologyRecovery());
        }
        if (config.getRequestedChannelMax() != null) {
            factory.setRequestedChannelMax(config.getRequestedChannelMax());
        }
        if (config.getRequestedFrameMax() != null) {
            factory.setRequestedFrameMax(config.getRequestedFrameMax());
        }
        Connection connection = null;
        try {
            connection = factory.newConnection();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (TimeoutException e) {
            throw new RuntimeException(e);
        }
        return connection;
    }

    protected void setupQueue() throws IOException {
        if (config.getQueueName() != null) {
            declareQueueDefaults(channel, config.getQueueName());
        }
    }

    private void declareQueueDefaults(Channel channel, String queueName) throws IOException {
        channel.queueDeclare(queueName, true, false, false, null);
    }
}
