import * as Crypto from "expo-crypto";

export async function cryptoPassword(password) {
  const Salt = "6%dkszcU*&lk@#$T#(lknkj.359";

  const encryptedPassword = await calcEncryptedPassword(password);

  return encryptedPassword;

  async function calcEncryptedPassword(password) {
    if (!password || password.length <= 7) {
      console.log("Invalid input");
      return;
    }

    const payload = password + Salt;
    const len = payload.length;

    const a1 = payload.substring(0, 3);
    const a2 = payload.substring(3, len - 3);
    const a3 = payload.substring(len - 3);

    const encryptedPassword = await Crypto.digestStringAsync(
      Crypto.CryptoDigestAlgorithm.MD5,
      a1 + a3 + a2,
      { encoding: Crypto.CryptoEncoding.HEX }
    );

    return encryptedPassword;
  }
}

export async function generateSignature(body) {
  const Salt = "6%dkszcU*&lk@#$T#(lknkj.359";

  const jsonBody = JSON.stringify(body);

  const signature = await calcSignature(jsonBody);

  return signature;

  async function calcSignature(s) {
    if (!s || s.length <= 20) {
      console.log("Invalid input");
      return;
    }

    const payload = s + Salt;
    const len = payload.length;

    const a1 = payload.substring(0, 10);
    const a2 = payload.substring(10, len - 10);
    const a3 = payload.substring(len - 10);

    const signature = await Crypto.digestStringAsync(
      Crypto.CryptoDigestAlgorithm.MD5,
      a1 + a3 + a2,
      { encoding: Crypto.CryptoEncoding.HEX }
    );

    return signature;
  }
}
