import './initPreviewableImage.scss';

export default () => {
    const NO_PHOTO = '/public/admin/img/no_photo.png';

    $('.previewable-image').each(function () {
        let previewableImage = $(this);
        let previewWidth = previewableImage.attr('data-preview-width');
        let wrapper = previewableImage.parent();
        let previewer = $('<img class="previewer img-fluid" />');

        wrapper.addClass('previewable-image-wrapper');
        previewableImage.wrap(`<p></p>`);
        wrapper.append(previewer);
        previewer.wrap(`<p class="previewer-wrapper img-thumbnail text-center" style="max-width: ${previewWidth || ''}px"></p>`);

        let previewerWrapper = previewer.parent();

        previewableImage.on('change', function () {
            let link = this.value || NO_PHOTO;

            previewerWrapper.addClass('loading');
            if (link) {
                $('<img />').attr('src', link).on({
                    load: function () {
                        previewer.attr('src', link);
                        previewerWrapper.removeClass('loading');
                    },
                    error: function () {
                        previewer.attr('src', NO_PHOTO);
                        previewerWrapper.removeClass('loading');
                    },
                });
            } else {
                previewer.attr('src', NO_PHOTO);
                previewerWrapper.removeClass('loading');
            }
        }).trigger('change');
    });
};
