package com.hubspot.singularity.data;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.atomic.AtomicValue;
import org.apache.curator.framework.recipes.atomic.DistributedAtomicLong;
import org.apache.curator.retry.RetryOneTime;

import com.google.common.base.Preconditions;
import com.google.common.base.Throwables;
import com.google.common.io.BaseEncoding;
import com.google.common.primitives.Longs;
import com.google.inject.Inject;

public class ExecutorIdGenerator {

  private final DistributedAtomicLong distributedGenerator;
  private final BaseEncoding encoder;
  
  private static final String COUNTER_PATH = "/executors/counter";
  
  @Inject
  public ExecutorIdGenerator(CuratorFramework curator) {
    this.distributedGenerator = new DistributedAtomicLong(curator, COUNTER_PATH, new RetryOneTime(1));
    this.encoder = BaseEncoding.base64Url().omitPadding().lowerCase();
  }
  
  public String getNextExecutorId() {
    try {
      AtomicValue<Long> atomic = distributedGenerator.increment();
      Preconditions.checkState(atomic.succeeded(), "Atomic increment did not succeed");
      return encoder.encode(Longs.toByteArray(atomic.postValue()));
    } catch (Throwable t) {
      throw Throwables.propagate(t);
    }
  }
  
}

@@ -218,20 +218,23 @@
 edAtomic
-Long
+Integer
 ;%0Aimport
@@ -365,93 +365,8 @@
 es;%0A
-import com.google.common.io.BaseEncoding;%0Aimport com.google.common.primitives.Longs;%0A
 impo
@@ -464,20 +464,23 @@
 edAtomic
-Long
+Integer
  distrib
@@ -514,28 +514,23 @@
 nal 
-BaseEncoding encoder
+char%5B%5D alphabet
 ;%0A  
@@ -720,20 +720,23 @@
 edAtomic
-Long
+Integer
 (curator
@@ -786,66 +786,32 @@
 his.
-encoder = BaseEncoding.base64Url().omitPadding().lowerCase
+alphabet = buildAlphabet
 ();%0A
@@ -883,20 +883,23 @@
 icValue%3C
-Long
+Integer
 %3E atomic
@@ -1040,40 +1040,28 @@
 urn 
-encoder.encode(Longs.toByteArray
+convertUsingAlphabet
 (ato
@@ -1076,17 +1076,16 @@
 Value())
-)
 ;%0A    %7D 
@@ -1156,10 +1156,637 @@
 %0A  %7D%0A  %0A
+  private String convertUsingAlphabet(int number) %7B%0A    final StringBuilder bldr = new StringBuilder();%0A    %0A    while (number %3E 0) %7B%0A      int remainder = number %25 alphabet.length;%0A      bldr.append(alphabet%5Bremainder%5D);%0A      number = number / alphabet.length;%0A    %7D%0A    %0A    return bldr.toString();%0A  %7D%0A  %0A  private char%5B%5D buildAlphabet() %7B%0A    final char%5B%5D alphabet = new char%5B36%5D;%0A    int c = 0;%0A %0A    // add integers%0A    for (int i = 48; i %3C 58; i++) %7B%0A      alphabet%5Bc++%5D = (char) i;%0A    %7D%0A    %0A    // add letters%0A    for (int i = 97; i %3C 123; i++) %7B%0A      alphabet%5Bc++%5D = (char) i;%0A    %7D%0A    %0A    return alphabet;%0A  %7D%0A%0A
 %7D%0A

fix the executor id generator.