package org.clicoy.bbs.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;

import java.util.Random;
import java.util.UUID;

/**
 * This is the what thing
 * Created by bjchenxx on 2015/2/3.
 */
public class ESUtils {
    public static String[] ES_HOSTS;
    public static Integer ES_PORT;
    public static TransportClient ES_CLUSTER_CLIENT;
    public static String ES_CLUSTER_NAME;
    public static Cfs CFS;
    public static String ES_INDEX;

    /**
     * Inital ElasticSearch connection .
     */
    public static void inital() {
        //init config config.properties
        CFS = new Cfs("config.properties");
        ES_HOSTS = CFS.getAsString("eshosts").split("_");
        ES_PORT = CFS.getAsInteger("es_port");
        ES_CLUSTER_NAME = CFS.getAsString("cluster.name");
        ES_INDEX = CFS.getAsString("es_index");
        //inital ElasticSearch cluster client.
        System.out.println("== inital ElasticSearch cluster connect...====================");
        Settings settings = ImmutableSettings.settingsBuilder()
                .put("client.transport.sniff", true).put("cluster.name",ES_CLUSTER_NAME).build();
        TransportClient client = new TransportClient(settings);
        InetSocketTransportAddress[] addresses = new InetSocketTransportAddress[ES_HOSTS.length];
        for (int i = 0;i<ES_HOSTS.length;i++){
            addresses[i] = new InetSocketTransportAddress(ES_HOSTS[i],ES_PORT);
        }
        ESUtils.ES_CLUSTER_CLIENT = client.addTransportAddresses(addresses);
        System.out.println("== ES client init success ! ===================================");
        System.out.println("== Inital Application Config ==================================");
        AppConfig.inital(CFS);
        System.out.println("== Inital Application Config Successfully ! ===================");
        System.out.println("== Inital REDIS Config     ====================================");
        RedisUtil.inital(CFS);
        System.out.println("== Inital REDIS Config Successfully !       ===================");
    }

    /**
     * this is parse one object to json string.
     * @param object
     * @return
     */
    public static  String json(Object object){
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.writeValueAsString(object);
        }catch (Exception e){
            return null;
        }
    }

    /**
     * Get uuid.
     * @return
     */
    public static String uuid(){
        return UUID.randomUUID().toString().replaceAll("-","");
    }

    /**
     * this is index the doc, single doc .<br/>
     * And it is mean to save one row data.
     * @param client
     * @param index
     * @param type
     * @param id
     * @param object
     * @return
     */
    public static boolean index(Client client,String index,String type,String id,Object object){
        IndexResponse response = null;
        if(id!=null&&index!=null&&type!=null)
            response = ES_CLUSTER_CLIENT.prepareIndex(index,type,id).setSource(json(object)).execute().actionGet();
        return response.isCreated();
    }

    public static boolean index(String index,String type,String id,Object object){
        return index(ES_CLUSTER_CLIENT,index,type,id,object);
    }

    /**
     * random word .
     * @param random
     * @return
     */
    public static String randWord(Random random){
        int len = random.nextInt(20)+1;
        StringBuffer buffer = new StringBuffer();
        for (int i= 1;i<=len;i++){
            buffer.append((char)(random.nextInt(25)+'a'));
        }
        return buffer.toString();
    }

    /**
     * As this method name . this is to create random words. nobody kown that words.
     * @param random
     * @return
     */
    public static String randWords(Random random){
        int len = random.nextInt(10)+1;
        StringBuffer buffer = new StringBuffer();
        for (int i= 1;i<=len;i++){
            if(i!=len)
                buffer.append(randWord(random)+" ");
            else
                buffer.append(randWord(random)+".");
        }
        return buffer.toString();
    }

    /**
     * Get one row Data response .
     * @param client
     * @param index
     * @param type
     * @param id
     * @return
     */
    public static GetResponse get(Client client,String index,String type,String id){
        return client.prepareGet(index, type, id).execute().actionGet();
    }
    public static GetResponse get(String index,String type,String id){
        return get(ES_CLUSTER_CLIENT,index,type,id);
    }

    /**
     * Delete index.
     * @param client
     * @param index
     * @param type
     * @param id
     * @return
     */
    public static boolean delete(Client client,String index,String type,String id){
        return client.prepareDelete(index,type,id).execute().actionGet().isFound();
    }

    /**
     * Use default connection to delete index.
     * @param index
     * @param type
     * @param id
     * @return
     */
    public static boolean delete(String index,String type,String id){
        return delete(ES_CLUSTER_CLIENT,index,type,id);
    }


    /**
     *
     * @param client
     */
    public static void  searchSingle(Client client){

    }

    public static void main(String[] args) {
        inital();
        //ES_CLUSTER_CLIENT.prepareGet("testindex", "test", "test215").execute().actionGet();
        long start = System.currentTimeMillis();
        GetResponse response = get(ES_CLUSTER_CLIENT,"testindex", "test", "test215");
        System.out.println("TIME:"+(System.currentTimeMillis()-start));
        System.out.println(response.getSourceAsString());
        start = System.currentTimeMillis();
        response = get(ES_CLUSTER_CLIENT,"testindex", "test", "test211");
        System.out.println("TIME:"+(System.currentTimeMillis()-start));
        System.out.println(response.getSourceAsString());
        response = get(ES_CLUSTER_CLIENT,"testindex", "test", "test261");
        System.out.println("TIME:"+(System.currentTimeMillis()-start));
        System.out.println(response.getSourceAsString());
        response = get(ES_CLUSTER_CLIENT,"testindex", "test", "test11");
        System.out.println("TIME:"+(System.currentTimeMillis()-start));
        System.out.println(response.getSourceAsString());
    }
}
