package com.hubspot.singularity.data;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.utils.ZKPaths;

import com.codahale.metrics.MetricRegistry;
import com.google.common.base.Optional;
import com.google.inject.Inject;
import com.hubspot.singularity.SingularityUserSettings;
import com.hubspot.singularity.config.SingularityConfiguration;
import com.hubspot.singularity.data.transcoders.Transcoder;

public class UserManager extends CuratorManager {

  private final Transcoder<SingularityUserSettings> settingsTranscoder;

  private static final String USER_ROOT = "/users";

  private static final String SETTINGS_ROOT = USER_ROOT + "/settings";

  @Inject
  public UserManager(CuratorFramework curator, SingularityConfiguration configuration, MetricRegistry metricRegistry,
                     Transcoder<SingularityUserSettings> settingsTranscoder) {
    super(curator, configuration, metricRegistry);
    this.settingsTranscoder = settingsTranscoder;
  }

  private String getUserSettingsPath(String userId) {
    return ZKPaths.makePath(SETTINGS_ROOT, userId);
  }

  public void updateUserSettings(String userId, SingularityUserSettings userSettings) {
    save(getUserSettingsPath(userId), userSettings, settingsTranscoder);
  }

  public Optional<SingularityUserSettings> getUserSettings(String userId) {
    return getData(getUserSettingsPath(userId), settingsTranscoder);
  }

  public void deleteUserSettings(String userId) {
    delete(getUserSettingsPath(userId));
  }

}

@@ -202,24 +202,106 @@
 on.base.
-Optional
+Charsets;%0Aimport com.google.common.base.Optional;%0Aimport com.google.common.io.BaseEncoding
 ;%0Aimport
@@ -630,16 +630,64 @@
 nscoder;
+%0A  private final SingularityValidator validator;
 %0A%0A  priv
@@ -1008,16 +1008,48 @@
 anscoder
+, SingularityValidator validator
 ) %7B%0A    
@@ -1145,16 +1145,212 @@
 scoder;%0A
+    this.validator = validator;%0A  %7D%0A%0A  private String encodeUserId(String userId) %7B%0A    validator.checkUserId(userId);%0A    return BaseEncoding.base64Url().encode(userId.getBytes(Charsets.UTF_8));%0A
   %7D%0A%0A  p
@@ -1443,23 +1443,37 @@
 S_ROOT, 
+encodeUserId(
 userId)
+)
 ;%0A  %7D%0A%0A 

Move encoding work for ZK userId into UserManager