package com.trs.digital.module.manager.configure;

import com.trs.hybase.client.TRSConnection;
import com.trs.hybase.client.params.ConnectParams;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

/**
 * @author fulj
 * @program: netInspect
 * @create: 2018-09-19 17:40
 **/
@Data
@Component
@Slf4j
public class HybaseFactory {

    @Value("${hybase.database.server}")
    private String url_;
    @Value("${hybase.database.user}")
    private String user_;
    @Value("${hybase.database.password}")
    private String pwd_;

    private static String url;
    private static String user;
    private static String pwd;

    private static ThreadLocal<TRSConnection> hybaseClient = new ThreadLocal<>();

    public static void setClient(TRSConnection connection) {
        hybaseClient.set(connection);
    }

    @PostConstruct
    public void init() {
        url = url_;
        user = user_;
        pwd = pwd_;
    }

    /**
     * 获取Hybase连接
     *
     * @return
     */
    public static TRSConnection getClient() {
        TRSConnection connection = hybaseClient.get();
        if (connection == null) {
            // 随机选择ip
            String[] split = url.split(";");
            int length = split.length;
            int nextInt = 0;
            if (length - 1 > 0) {
                Random rand = new Random();
                nextInt = rand.nextInt(split.length - 1);
            }
            List<String> asList = Arrays.asList(split);
            String link = asList.get(nextInt);
            String serverList = assemblyServerList(url, "", link);
            connection = new TRSConnection(serverList, user, pwd, new ConnectParams());
            setClient(connection);
        }
        return connection;
    }

    /**
     * 装配服务器列表
     *
     * @param host   地址
     * @param port   端口
     * @param server 服务器列表
     * @return String
     */
    private static String assemblyServerList(String host, String port, String server) {
        StringBuilder serverList = new StringBuilder();
        if (StringUtils.isEmpty(server)) {
            serverList = new StringBuilder("http://" + host + ":" + port);
        } else {
            String[] serverArray = server.split(";");
            for (int i = 0; i < serverArray.length; i++) {
                serverList.append("http://").append(serverArray[i]);
                if (i < serverArray.length - 1) {
                    serverList.append(";");
                }
            }
        }
        return serverList.toString();
    }

    public static void clean() {
        try {
            hybaseClient.get().close();
        } catch (Exception ignore) {

        }
        hybaseClient.remove();
    }

}
