package com.liquidnet.service.platform.utils;

import com.liquidnet.commons.lang.util.CollectionUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Random;

/**
 * 随机昵称（逻辑对齐 adam {@code com.liquidnet.service.adam.util.NknameUtil}）。
 */
public class NknameUtil {
    private static final Logger log = LoggerFactory.getLogger(NknameUtil.class);

    private static int bound;
    private static final List<String> nknameList;
    private static final String nknamePrefix = "宇航员";
    private static final Random random = new Random();
    static {
        nknameList = reload();
    }

    public static List<String> reload() {
        List<String> list = CollectionUtil.arrayListString();
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader bufferedReader = null;
        try {
            inputStream = NknameUtil.class.getClassLoader().getResourceAsStream("META-FIL/library_nickname.csv");
            inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
            bufferedReader = new BufferedReader(inputStreamReader);

            String line;
            while ((line = bufferedReader.readLine()) != null) {
                int l = StringUtils.length(line);
                if (l == 0) {
                    break;
                }
                if (l > 11) {
                    line = line.substring(0, 11);
                }
                list.add(line);
            }
            if (!CollectionUtils.isEmpty(list)) {
                bound = list.size();
            }
        } catch (IOException e) {
            log.error("Read CSV[library_nickname.csv] failure.", e);
        } finally {
            try {
                if (null != bufferedReader) bufferedReader.close();
                if (null != inputStreamReader) inputStreamReader.close();
                if (null != inputStream) inputStream.close();
            } catch (IOException e) {
                log.error("Close stream failure.", e);
            }
        }
        log.info("Load nkname init:{}~{}", list.size(), bound);
        return list;
    }

    public static String randomNkname() {
        return nknamePrefix + nknameList.get(random.nextInt(bound));
    }
}
