import md5 from 'md5';
import { AccessToken2, ServiceApaas, ServiceChat, ServiceRtm } from './AccessToken2';

export class EducationTokenBuilder {
  /**
   * build user room token
   * @param appId - The App ID issued to you by Agora.
   * @param appCertificate - Certificate of the application that you registered in the Agora Dashboard.
   * @param roomUuid - The room's id, must be unique.
   * @param userUuid - The user's id, must be unique.
   * @param role - The user's role.
   * @param expire - represented by the number of seconds elapsed since now.
   * @returns The user room token.
   */
  public static buildRoomUserToken(appId: string, appCertificate: string, roomUuid: string, userUuid: string, role: number, expire: number): string {
    const accessToken = new AccessToken2(appId, appCertificate, 0, expire);

    const chatUserId = md5(userUuid);
    const apaasService = new ServiceApaas(roomUuid, userUuid, role);
    accessToken.add_service(apaasService);

    const rtmService = new ServiceRtm(userUuid);
    rtmService.add_privilege(ServiceRtm.kPrivilegeLogin, expire);
    accessToken.add_service(rtmService);

    const chatService = new ServiceChat(chatUserId);
    chatService.add_privilege(ServiceChat.kPrivilegeUser, expire);
    accessToken.add_service(chatService);

    return accessToken.build();
  }

  /**
   * build user token
   * @param appId - The App ID issued to you by Agora.
   * @param appCertificate - Certificate of the application that you registered in the Agora Dashboard.
   * @param userUuid - The user's id, must be unique.
   * @param expire - represented by the number of seconds elapsed since now.
   * @returns The user token.
   */
  public static buildUserToken(appId: string, appCertificate: string, userUuid: string, expire: number): string {
    const accessToken = new AccessToken2(appId, appCertificate, 0, expire);
    const apaasService = new ServiceApaas('', userUuid);
    apaasService.add_privilege(ServiceApaas.PRIVILEGE_USER, expire);
    accessToken.add_service(apaasService);

    return accessToken.build();
  }

  /**
   * build app token
   * @param appId - The App ID issued to you by Agora.
   * @param appCertificate - Certificate of the application that you registered in the Agora Dashboard.
   * @param expire - represented by the number of seconds elapsed since now.
   * @returns The app token.
   */
  public static buildAppToken(appId: string, appCertificate: string, expire: number): string {
    const accessToken = new AccessToken2(appId, appCertificate, 0, expire);
    const apaasService = new ServiceApaas();
    apaasService.add_privilege(ServiceApaas.PRIVILEGE_APP, expire);
    accessToken.add_service(apaasService);

    return accessToken.build();
  }
}
