define(['jquery', 'core/mimetype', 'ui/mediaEditor/plugins/mediaAlignment/helper', 'ui/mediaEditor/mediaEditorComponent', 'lodash'], function (jquery, mimeType, alignmentHelper, mediaEditorComponent, _) { 'use strict';

    mimeType = mimeType && Object.prototype.hasOwnProperty.call(mimeType, 'default') ? mimeType['default'] : mimeType;
    alignmentHelper = alignmentHelper && Object.prototype.hasOwnProperty.call(alignmentHelper, 'default') ? alignmentHelper['default'] : alignmentHelper;
    mediaEditorComponent = mediaEditorComponent && Object.prototype.hasOwnProperty.call(mediaEditorComponent, 'default') ? mediaEditorComponent['default'] : mediaEditorComponent;
    _ = _ && Object.prototype.hasOwnProperty.call(_, 'default') ? _['default'] : _;

    /*
     * This program is free software; you can redistribute it and/or
     * modify it under the terms of the GNU General Public License
     * as published by the Free Software Foundation; under version 2
     * of the License (non-upgradable).
     *
     * This program is distributed in the hope that it will be useful,
     * but WITHOUT ANY WARRANTY; without even the implied warranty of
     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     * GNU General Public License for more details.
     *
     * You should have received a copy of the GNU General Public License
     * along with this program; if not, write to the Free Software
     * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
     *
     * Copyright (c) 2022 (original work) Open Assessment Technologies SA (under the project TAO-PRODUCT);
     */
    function getImage(widget) {
      let $img = widget.$original;
      let img = widget.element;
      if (widget.element.is('figure')) {
        $img = widget.$original.find('img');
        img = _.find(widget.element.getBody().elements, elem => elem.is('img'));
      }
      return {
        $img,
        img
      };
    }

    /*
     * This program is free software; you can redistribute it and/or
     * modify it under the terms of the GNU General Public License
     * as published by the Free Software Foundation; under version 2
     * of the License (non-upgradable).
     *
     * This program is distributed in the hope that it will be useful,
     * but WITHOUT ANY WARRANTY; without even the implied warranty of
     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     * GNU General Public License for more details.
     *
     * You should have received a copy of the GNU General Public License
     * along with this program; if not, write to the Free Software
     * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
     *
     * Copyright (c) 2021 (original work) Open Assessment Technologies SA (under the project TAO-PRODUCT);
     */
    const mediaSizer = function mediaSizer(media, widget) {
      const {
        img,
        $img
      } = getImage(widget);
      const $mediaSpan = widget.$container;
      if (img.data('responsive') !== media.responsive) {
        // switch between responsive and absolute values
        img.data('responsive', media.responsive);
        // clean styles from prev mode
        $img.removeAttr('width');
        $img.removeAttr('height');
        $mediaSpan[0].removeAttribute('style');
      }
      _(['width', 'height']).forEach(function (sizeAttr) {
        let val;
        if (media[sizeAttr] === '' || typeof media[sizeAttr] === 'undefined' || media[sizeAttr] === null) {
          img.removeAttr(sizeAttr);
          $img.removeAttr(sizeAttr);
          $mediaSpan.css(sizeAttr, '');
        } else {
          val = Math.round(media[sizeAttr]);
          if (media.responsive) {
            val += '%';
            img.attr(sizeAttr, val);
            $img.attr(sizeAttr, '100%');
          } else {
            img.attr(sizeAttr, val);
            $img.attr(sizeAttr, val);
          }
          if (media.responsive || sizeAttr === 'width') {
            $mediaSpan.css(sizeAttr, val);
          }
        }
        //trigger choice container size adaptation
        widget.$container.trigger('contentChange.qti-widget');
      });
    };

    /*
     * This program is free software; you can redistribute it and/or
     * modify it under the terms of the GNU General Public License
     * as published by the Free Software Foundation; under version 2
     * of the License (non-upgradable).
     *
     * This program is distributed in the hope that it will be useful,
     * but WITHOUT ANY WARRANTY; without even the implied warranty of
     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     * GNU General Public License for more details.
     *
     * You should have received a copy of the GNU General Public License
     * along with this program; if not, write to the Free Software
     * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
     *
     * Copyright (c) 2021 (original work) Open Assessment Technologies SA (under the project TAO-PRODUCT);
     */
    const getMedia = (imgQtiElement, $imgNode, cb) => {
      //init data-responsive:
      if (typeof imgQtiElement.data('responsive') === 'undefined') {
        if (imgQtiElement.attr('width') && !/[0-9]+%/.test(imgQtiElement.attr('width'))) {
          imgQtiElement.data('responsive', false);
        } else {
          imgQtiElement.data('responsive', true);
        }
      }
      if (typeof imgQtiElement.attr('original-width') !== 'undefined' && typeof imgQtiElement.attr('original-height') !== 'undefined' && typeof imgQtiElement.attr('type') !== 'undefined' && typeof imgQtiElement.attr('src') !== 'undefined' && typeof imgQtiElement.attr('width') !== 'undefined' && typeof imgQtiElement.attr('height') !== 'undefined') {
        cb({
          $node: $imgNode,
          type: imgQtiElement.attr('type'),
          src: imgQtiElement.attr('src'),
          width: imgQtiElement.attr('width'),
          height: imgQtiElement.attr('height'),
          responsive: imgQtiElement.data('responsive')
        });
      } else {
        mimeType.getResourceType($imgNode.attr('src'), function (err, type) {
          imgQtiElement.attr('type', type);
          cb({
            $node: $imgNode,
            type: imgQtiElement.attr('type'),
            src: imgQtiElement.attr('src'),
            width: imgQtiElement.attr('width'),
            height: imgQtiElement.attr('height'),
            responsive: imgQtiElement.data('responsive')
          });
        });
      }
    };
    const getMediaCb = (media, widget, mediaEditor, options) => {
      const $mediaResizer = widget.$form.find('.img-resizer');
      media.$container = widget.$container.parents('.widget-box');
      if (media.$container.length) {
        // eslint-disable-next-line no-unused-vars
        mediaEditor = mediaEditorComponent($mediaResizer, media, options).on('change', function (nMedia) {
          media = nMedia;
          widget.$original.prop('style', null); // not allowed by qti
          widget.$original.removeAttr('style');
          alignmentHelper.positionFloat(widget, media.align);
          mediaSizer(media, widget);
          widget.$original.removeClass('hidden');
        });
      }
    };
    function initMediaEditor(widget, mediaEditor, options) {
      if (mediaEditor) {
        mediaEditor.destroy();
      }
      if (!widget.$form.find('input[name=src]').val()) {
        return;
      }
      const {
        img,
        $img
      } = getImage(widget);
      getMedia(img, $img, m => getMediaCb(m, widget, mediaEditor, options));
    }

    return initMediaEditor;

});
