import md5 from 'md5';

export class SignalingToken {
  /**
   * Get Signaling Token
   * @param appid - The App ID
   * @param appcertificate - The App Certificate
   * @param account - The user account
   * @param validTimeInSeconds - Valid time in seconds
   * @returns The Signaling Token
   */
  public static get(appid: string, appcertificate: string, account: string, validTimeInSeconds: number): string {
    const expiredTime = parseInt(String(new Date().getTime() / 1000), 10) + validTimeInSeconds;
    const token_items: string[] = [];

    // append SDK VERSION
    token_items.push('1');

    // append appid
    token_items.push(appid);

    // expired time
    token_items.push(String(expiredTime));

    // md5 account + appid + appcertificate + expiredtime
    token_items.push(md5(account + appid + appcertificate + expiredTime));

    return token_items.join(':');
  }

  /**
   * Convenience function to get token valid within 1 day
   * @param appid - The App ID
   * @param appcertificate - The App Certificate
   * @param account - The user account
   * @returns The Signaling Token valid for 1 day
   */
  public static get1DayToken(appid: string, appcertificate: string, account: string): string {
    return SignalingToken.get(appid, appcertificate, account, 3600 * 24);
  }
}

export default SignalingToken;
