;( function($, window, document, undefined)
{
    'use strict';

    var pluginName = 'igniteEditor',
        defaults = {
            csrfToken: '',
            templateCode: '',
            datetimepicker: {
                selector: '.datepicker',
                options: {
                    format: 'YYYY-MM-DD HH:mm:ss',
                    icons: {
                        time: 'fa-solid fa-clock',
                        date: 'fa-solid fa-calendar',
                        up: 'fa-solid fa-arrow-up',
                        down: 'fa-solid fa-arrow-down'
                    }
                }
            },
            summernote: {
                selector: '.editor',
                toolbar: [
                    ['style', ['style', 'bold', 'italic', 'underline', 'clear']],
                    ['font', ['strikethrough', 'superscript', 'subscript']],
                    ['para', ['ul', 'ol', 'paragraph']],
                    ['insert', ['picture', 'link', 'mediaManager']],
                    ['misc', ['fullscreen', 'codeview', 'undo', 'redo']]
                ]
            }
        };

    function Plugin (element, options) {
        this.element = element;
        this.settings = $.extend({}, defaults, options);
        this._defaults = defaults;
        this._name = pluginName;
        this.init();
    }

    $.extend(Plugin.prototype, {
        init: function() {
            this.initDateTimePickers();
            this.initWysiwyg();
            this.initProtection();
            this.initCodeGenerator();
        },
        initCodeGenerator: function() {
            var $title = $('#form-content-title');
            var $code = $('#form-content-code');

            if ($code.attr('disabled') || $code.attr('readonly')) {
                return;
            }

            $title.on('keyup', function() {
                $code.val(
                    $.trim($title.val())
                    .toLowerCase()
                    .replace(/[^a-z0-9]+|\s+/gmi, '-')
                    .replace(/[\-]+$/g, '')
                );
            });
        },
        initProtection: function() {
            var $isProtected = $('#form-content-is-protected');
            var $allowedGroups = $('#form-content-allowed-groups');

            $isProtected.on('change', function(evt) {
                var $checkbox = $(this);
                if ($checkbox.is(':checked')) {
                    $allowedGroups.removeClass('hide');
                } else {
                    $allowedGroups.addClass('hide');
                }
            });
        },
        initDateTimePickers: function() {
            var $dateTimePickers = $(this.settings.datetimepicker.selector);

            if (! $dateTimePickers.length) {
                return $dateTimePickers;
            }

            if (typeof $.fn.datetimepicker !== 'function') {
                console.warn('igniteEditor: datetimepicker plugin is unavailable; skipping initialization.');
                return $dateTimePickers;
            }

            return $dateTimePickers.datetimepicker(this.settings.datetimepicker.options);
        },
        initWysiwyg: function() {
            var self = this;
            var $editor = $(this.settings.summernote.selector);

            $editor.summernote({
                dialogsInBody: true,
                disableDragAndDrop: true,
                toolbar: this.settings.summernote.toolbar,
                lang: 'en-US',
                popover: {
                    image: [
                        ['image', ['resizeFull', 'resizeHalf', 'resizeQuarter', 'resizeNone']],
                        ['float', ['floatLeft', 'floatRight', 'floatNone']],
                        ['remove', ['removeMedia']],
                        ['custom', ['imageAttributes']]
                    ]
                },
                callbacks: {
                    onImageUpload: function(files) {
                        try {
                            window.MediaUpload(files, function (url) {
                                $editor.summernote('insertImage', url);
                            });
                        } catch (e) {
                            console.log(e);
                        }
                    }
                }
            });
            $(this.element).on('submit', function(e) {
                if ($editor.summernote('codeview.isActivated')) {
                    $editor.summernote('codeview.deactivate');
                }
                $editor.focus().trigger('focus');
            });

            return $editor;
        }
    });

    $.fn[pluginName] = function(options) {
        return this.each( function() {
            if (! $.data(this, 'plugin_' + pluginName)) {
                $.data(this, 'plugin_' + pluginName, new Plugin(this, options));
            }
        });
    };

} )(jQuery, window, document);
