package org.knowm.xchange.bitmex.service;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Mac;
import javax.ws.rs.FormParam;

import org.knowm.xchange.service.BaseParamsDigest;

import net.iharder.Base64;
import si.mazi.rescu.RestInvocation;

public class BitmexDigest extends BaseParamsDigest {

  private String apiKey;

  /**
   * Constructor
   *
   * @param secretKeyBase64
   * @param apiKey @throws IllegalArgumentException if key is invalid (cannot be base-64-decoded or the decoded key is invalid).
   */

  private BitmexDigest(byte[] secretKeyBase64) {

    super(secretKeyBase64, HMAC_SHA_512);
  }

  public static BitmexDigest createInstance(String secretKeyBase64) {

    try {
      if (secretKeyBase64 != null)
        return new BitmexDigest(Base64.decode(secretKeyBase64.getBytes()));
    } catch (IOException e) {
      throw new IllegalArgumentException("Could not decode Base 64 string", e);
    }
    return null;
  }

  @Override
  public String digestParams(RestInvocation restInvocation) {

    MessageDigest sha256;
    try {
      sha256 = MessageDigest.getInstance("SHA-256");
    } catch (NoSuchAlgorithmException e) {
      throw new RuntimeException("Illegal algorithm for post body digest. Check the implementation.");
    }
    sha256.update(restInvocation.getParamValue(FormParam.class, "nonce").toString().getBytes());
    sha256.update(restInvocation.getRequestBody().getBytes());

    Mac mac512 = getMac();
    mac512.update(("/" + restInvocation.getPath()).getBytes());
    mac512.update(sha256.digest());

    return Base64.encodeBytes(mac512.doFinal()).trim();

  }

  private BitmexDigest(String secretKeyBase64, String apiKey) {

    super(secretKeyBase64, HMAC_SHA_256);
    this.apiKey = apiKey;
  }

  public static BitmexDigest createInstance(String secretKeyBase64, String apiKey) {

    return secretKeyBase64 == null ? null : new BitmexDigest(secretKeyBase64, apiKey);
  }

}

@@ -40,36 +40,8 @@
 e;%0A%0A
-import java.io.IOException;%0A
 impo
@@ -72,16 +72,16 @@
 Digest;%0A
+
 import j
@@ -118,16 +118,41 @@
 ception;
+%0Aimport java.util.Base64;
 %0A%0Aimport
@@ -257,35 +257,8 @@
 t;%0A%0A
-import net.iharder.Base64;%0A
 impo
@@ -731,28 +731,16 @@
 e64) %7B%0A%0A
-    try %7B%0A  
     if (
@@ -763,19 +763,19 @@
 != null)
-%0A  
+ %7B%0A
       re
@@ -803,16 +803,32 @@
 (Base64.
+getUrlDecoder().
 decode(s
@@ -860,118 +860,8 @@
 ));%0A
-    %7D catch (IOException e) %7B%0A      throw new IllegalArgumentException(%22Could not decode Base 64 string%22, e);%0A
     
@@ -1511,19 +1511,38 @@
 e64.
-encodeBytes
+getUrlEncoder().encodeToString
 (mac

switch API keys to url-safe base64 encoding, which is the scheme used by bitmex