/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

import nodeFetch from 'node-fetch';
import UserAgentError from "../UserAgentError";
import ClaimObject, { ClaimDescription } from "./ClaimObject";

/**
 * Class containing data for displaying an approval prompt in User Agent app.
 */
export default class ClaimUIAttributes {

  /**
   * Issuer name of the credential.
   */
  public issuerName: string;

  /**
   * Name of the credential.
   */
  public claimName: string;

  /**
   * Background color of the credential.
   */
  public hexBackgroundColor: string;

  /**
   * Font color of the credential.
   */
  public hexFontColor: string;

  /**
   * Logo formatted according to Claim Spec.
   */
  public logo: {
    sourceUri: {
      uri: string,
      description: string
    }
  };

  /**
   * Claim Descriptions for claims contained in Claim Object.
   */
  public claimDescriptions: ClaimDescription[];

  /**
   * Private Constructor for collecting PromptData.
   * @param claimUIAttributes 
   */
  private constructor(claimUIAttributes: any) {
    this.hexBackgroundColor = claimUIAttributes.hexBackgroundColor;
    this.hexFontColor = claimUIAttributes.hexFontColor;
    this.claimName = claimUIAttributes.claimName;
    this.issuerName = claimUIAttributes.issuerName;
    this.claimDescriptions = claimUIAttributes.claimDescriptions;
    this.logo = claimUIAttributes.logo;
  }

  /**
   * Gets prompt data from claimObject in OidcRequest.
   * note: think about whether this should take in an Claim Object instead.
   * @param {ClaimObject} claimObject claimObject used to construct PromptData Object.
   * @returns {PromptData}
   */
  public static async create(claimObject: ClaimObject): Promise<ClaimUIAttributes> {
    const claimClass = await this.fetchClaimClass(claimObject.claimClass);
    const attributes = {
      hexBackgroundColor: claimClass.hexBackgroundColor,
      hexFontColor: claimClass.hexFontColor,
      claimName: claimClass.claimName,
      issuerName: claimClass.issuerName,
      claimDescriptions: claimObject.claimDescriptions,
      logo: claimClass.claimLogo
    };
    return new ClaimUIAttributes(attributes);
  }

  /**
   * Get Claim Class from Endpoint.
   * @param {string} claimClassUrl url that contains claim class.
   */
  private static async fetchClaimClass(claimClassUrl: string) {
    const response = await nodeFetch(claimClassUrl);
    if (response.status !== 200) {
      throw new UserAgentError(`Failed to GET claim class at: ${claimClassUrl}`);
    }
    return response.json();
  }
}
