package com.devulex.eventorage.config

import org.elasticsearch.client.transport.TransportClient
import org.elasticsearch.common.settings.Settings
import org.elasticsearch.common.transport.InetSocketTransportAddress
import org.elasticsearch.transport.client.PreBuiltTransportClient
import org.jetbrains.ktor.config.ApplicationConfig
import java.net.InetAddress
import java.net.UnknownHostException

@Throws(UnknownHostException::class)
fun connectElasticsearch(applicationConfig: ApplicationConfig): TransportClient {

    val clusterName = applicationConfig.property("elasticsearch.cluster.name")

    val settings = Settings.builder()
            .put("cluster.name", clusterName.getString())
            .put("client.transport.sniff", true)
            .build()

    val client = PreBuiltTransportClient(settings)

    val clusterNodes = applicationConfig.property("elasticsearch.cluster.nodes").getList()
    if (clusterNodes.isEmpty()) {
        throw NoSuchElementException("List nodes Elasticsearch is empty.")
    }
    for (node in clusterNodes) {
        val nodeSplit = node.split(":")
        if (nodeSplit.size != 2) {
            throw IllegalArgumentException("Node address should have delimiter \":\" between host and port values.")
        }
        val host = nodeSplit.first()
        val port = nodeSplit.last().toInt()
        client.addTransportAddress(InetSocketTransportAddress(InetAddress.getByName(host), port))
    }

    return client
}

fun disconnectElasticsearch(client: TransportClient) {
    client.close();
}
