/**
 * @file
 * Javascript functionality for component download.
 */

(function ($, Drupal, once) {

  'use strict';

  Drupal.componentDownload = Drupal.componentDownload || {};
  Drupal.behaviors.download = {
    attach: function (context) {
      Drupal.componentDownload.download(context);
    }
  }
  Drupal.componentDownload.download = function (context) {
    const $download = $(once('downloadItems', '.component-builder.component-item--type-download', context));
    if ($download.length > 0) {
      $download.each(function () {
        const $this = $(this);
        const $get_href = $this.find("div.field--type-file > span > a").attr("href");
        const $get_type = $this.find("div.field--type-file > span > a").attr("type");
        const $button = $this.find('.link-download');
        $button.attr("href", $get_href);
        $button.attr("type", $get_type);

        let $text = $this.find("div.field--type-file > span > a").text()
        let $name_file = $text.split('.')[0];
        $this.find('h3').text($name_file);
        let $created = $this.find("div.field.field--name-created.field--type-created.field--label-hidden.field__item").text();
        $this.find('p.created').text('Lastest version ' + $created);

        const $extension_music = ['mp3', 'wav', 'aac', 'flac'];
        const $extension_image = ['png', 'gif', 'jpg', 'jpeg'];
        const type = $text.split('.')[1];
        var url = '';
        const default_types = ['xlsx', 'txt', 'docx', 'pdf']
        const icons = drupalSettings.components.download.icons;
        if (default_types.includes(type)) {
          url = icons[type];
        } else if ($extension_music.includes(type)) {
          url = icons['music'];
        } else if ($extension_image.includes(type)) {
          url = icons['image'];
        }
        if (!url) {
          url = icons['file'];
        }
        url = window.location.origin + '/' + url;
        $this.find('div.image-file').html(`<img src = "${url}" alt = "Icon ${type}" />`);
      })
    }
  }

})(jQuery, Drupal, once);
