package pub.pjoc.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.UnknownHostException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author xiongyingqi
 * @since 16-9-21 下午8:16
 */
public abstract class SequenceGenerator {
  private static final Logger logger = LoggerFactory.getLogger(SequenceGenerator.class);
  private static final String FORMAT_STRING = "yyyyMMddHHmmssSSS";
  private static AtomicInteger index = new AtomicInteger();
  // machine number
  private static String widthMachineNumber = "";

  static {
    try {
      widthMachineNumber = NetWorkUtils.getWidthMachineNumber();
    } catch (UnknownHostException e) {
      logger.error("", e);
    }
  }


  private static String getIndexString(int width) {
    int max = (int) Math.pow(10, width) - 1;
    int number = index.getAndIncrement();
    int rs = number % max;
    if (rs < 0) {
      rs = -rs;
    }

    return StringUtils.fillZero(rs + "", width);
  }

  /**
   * 生成序列号。默认100w并发
   *
   * @return 序列号
   */
  public static String generateSequence() {
    return generateSequence(1000000);
  }

  /**
   * 指定并发度并且生成序列号
   *
   * @param concurrent 并发度
   * @return 序列号
   */
  public static String generateSequence(int concurrent) {
    StringBuilder builder = new StringBuilder();
    String dateString = getDateString();
    builder.append(dateString);

//        Long machineNumber = Long.parseLong(widthMachineNumber);
//        String machineNumberHex = Long.toHexString(machineNumber);
    builder.append(widthMachineNumber);
    double log = Math.log10(concurrent);
    String indexString = getIndexString((int) log);
    builder.append(indexString);

    return builder.toString();
  }


  private static String getDateString() {
    DateFormat format = new SimpleDateFormat(FORMAT_STRING);
    String date = format.format(new Date());
    return date;
  }

}
