{"size": 1959, "ext": "js", "max_stars_repo_path": "wwwroot/js/imageRepository.js", "max_stars_repo_name": "JornWildt/SolidRC", "max_stars_repo_stars_event_min_datetime": "2018-11-05T14:12:42.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-31T04:46:09.000Z", "max_issues_repo_path": "wwwroot/js/imageRepository.js", "max_issues_repo_name": "JornWildt/SolidRC", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "wwwroot/js/imageRepository.js", "max_forks_repo_name": "JornWildt/SolidRC", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 3, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 24.4875, "max_line_length": 108, "alphanum_fraction": 0.6110260337}
/** Image repository with CRUD methods for images.
 */
class ImageRepository extends ORDFMapper
{
  constructor(baseUrl)
  {
    super();
    this.baseUrl = baseUrl;
  }


  /** Add image.
   * 
   * @param {File object} image - Image to upload (represented as a File object from a file input element).
   */
  async addImage(image, name)
  {
    if (image)
    {
      let imageUrlName = this.generateImageName(image.name, name);
      let imageUrl = this.baseUrl + imageUrlName;

      await this.fetcher.webOperation('PUT', imageUrl,
      {
        body: image,
        contentType: image.type,
        credentials: 'include'
      });

      return imageUrl;
    }

    return null;
  }


  async updateImage(image, url)
  {
    return this.fetcher.webOperation('PUT', url,
    {
      body: image,
      contentType: image.type,
      credentials: 'include'
    });
  }


  /** Delete image.
   * 
   * @param {URL string} imageUrl - Image URL.
   */
  async deleteImage(imageUrl)
  {
    return this.deleteObject(imageUrl);
  }


  generateImageName(orgName, requiredName)
  {
    // If required name has no extension then get extension from original name
    let dotPos = requiredName.lastIndexOf('.');
    if (dotPos < 0)
    {
      dotPos = orgName.lastIndexOf('.');
      let nameExt = (dotPos >= 0 ? orgName.substring(dotPos, Infinity) : '');
      requiredName = requiredName + nameExt;
    }

    // Normally we do not allow dots in URLs as the Solid server uses that for content type(!)
    // So remove extension before creating name and then add the extension again afterwards.
    dotPos = requiredName.lastIndexOf('.');
    let nameExt = (dotPos >= 0 ? requiredName.substring(dotPos, Infinity) : '');
    requiredName = requiredName.substring(0, dotPos);

    let name = this.generateValidUrlName(requiredName).toLowerCase() + nameExt;
    return name;
  }
}

