/** @file
 * @author Edouard DUPIN
 * @copyright 2018, Edouard DUPIN, all right reserved
 * @license PROPRIETARY (see license file)
 */
import { string } from 'zod';

import { RESTUrl } from '@/back-api';
import { environment } from '@/environment';
import { getRestConfig } from '@/service/session';
import { isArrayOf, isString } from '@/utils/validator';

export namespace DataUrlAccess {
  /**
   * Retrieve the Cover URL of a specific data id
   * @param coverId Id of te cover
   * @returns the url of the cover
   */
  export const getUrl = (dataId: string, optionalName?: string): string => {
    if (!optionalName) {
      const url = RESTUrl({
        restModel: {
          endPoint: 'data/{dataId}',
          tokenInUrl: true,
        },
        restConfig: getRestConfig(),
        params: {
          dataId,
        },
      });
      console.log(`get URL = ${url}`);
      if (environment?.replaceDataToRealServer === true) {
        return url.replace('http://localhost:19080', 'https://atria-soft.org');
      }
      return url;
    }
    const url = RESTUrl({
      restModel: {
        endPoint: 'data/{dataId}/{optionalName}',
        tokenInUrl: true,
      },
      restConfig: getRestConfig(),
      params: {
        dataId,
        optionalName,
      },
    });
    if (environment?.replaceDataToRealServer === true) {
      return url.replace('http://localhost:19080', 'https://atria-soft.org');
    }
    return url;
  };
  /**
   * Retrieve the list Cover URL of a specific data id
   * @param coverId Id of te cover
   * @returns the url of the cover
   */
  export const getListUrl = (dataIds?: string[]): string[] | undefined => {
    if (!isArrayOf(dataIds, isString) || dataIds.length === 0) {
      return undefined;
    }
    let covers: string[] = [];
    for (let iii = 0; iii < dataIds.length; iii++) {
      covers.push(getUrl(dataIds[iii]));
    }
    return covers;
  };
  /**
   * Retrieve the thumbnail cover URL of a specific data id
   * @param coverId Id of te cover
   * @returns the url of the cover
   */
  export const getThumbnailUrl = (coverId: string): string => {
    const url = RESTUrl({
      restModel: {
        endPoint: 'data/thumbnail/{coverId}',
        tokenInUrl: true,
      },
      restConfig: getRestConfig(),
      params: {
        coverId,
      },
    });
    if (environment?.replaceDataToRealServer === true) {
      return url.replace('http://localhost:19080', 'https://atria-soft.org');
    }
    return url;
  };
  /**
   * Retrieve the list thumbnail cover URL of a specific data id
   * @param coverId Id of te cover
   * @returns the url of the cover
   */
  export const getListThumbnailUrl = (
    dataIds?: string[]
  ): string[] | undefined => {
    if (!isArrayOf(dataIds, isString) || dataIds.length === 0) {
      return undefined;
    }
    let covers: string[] = [];
    for (let iii = 0; iii < dataIds.length; iii++) {
      covers.push(getThumbnailUrl(dataIds[iii]));
    }
    return covers;
  };
}
