(function ($) {
    /* Define modal management plugin */
    ModalManagement = function (options) {
        /* Set global variable this in plugin*/
        var _this = this;

        /* Set default properties*/
        var defaults = {
            modal_selector: null,
            form_selector: null,
            form_task: 'create',
            form_rules: {},
            form_messages: {},
            form_fill_on_ajax: true,
            ajax_use: true,
            ajax_getOne: '',
            ajax_getAll: '',
            ajax_create: '',
            ajax_update: '',
            ajax_delete: '',
        };
        /* define plugin settings */
        var settings = {};
        this._entity;
        this._onsave;
        this._ongetoneentity;
        this._onclosemodal;
        /* Handles if closure function is provided as function parameter if not run provided code */
        var ifClosureExec = function (data) {
            if (data instanceof Function) {
                data();
            }
        };
        /* Set plugin property */
        var setProp = function (prop, val) {
            if (settings.hasOwnProperty(prop)) {
                if (settings[prop] == '' || settings[prop] == null || (typeof settings[prop] == typeof val)) {
                    settings[prop] = val;
                } else {
                    console.error("Property " + prop + " is invalid");
                }
            } else {
                console.error("Property " + prop + " is unsetable");
            }
        }
        /* Handle form with validation and submit hendler */
        var formHendler = function (executableFunc) {
            _this.onSaveEntity(executableFunc);
            settings.form_selector.validate({
                "rules": settings.form_rules,
                errorPlacement: function (error, element) {
                    error.insertAfter(element);
                },
                errorClass: 'text-danger',
                submitHandler: function (form) {
                    
                    if (_this.isTask('create')) {
                        _this.createEntity();
                    }
                    if (_this.isTask('update')) {
                        _this.updateEntity();
                    }
                    if (_this.isTask('delete')) {
                        _this.deleteEntity();
                    }
                    return false;
                }
            });
        };
        /* Fill modal form with relevant data*/
        var fillForm = function (data) {
            let form = settings.form_selector;
            $.each(data, function (key, value) {
                form.find(`[name="${key}"]`).val(value);
            });
        };
        /* Clear modal form from all data*/
        var clearForm = function () {
            settings.form_selector[0].reset();
        };
        /* Initialize plugin */
        this.init = function (options) {
            $.extend(settings, defaults);
            if (options instanceof Object) {
                for (prop in options) {
                    _this.setProperty(prop, options[prop]);
                }
            }
            /* Listener when modal iz closed */
            if (settings.modal_selector) {
                settings.modal_selector.on('hidden.bs.modal', function () {
                    if (_this._onclosemodal != undefined) {
                        _this._onclosemodal();
                    } else {
                        clearForm();
                    }
                });
            }
            return _this;
        };
        /* Check what task is set */
        this.isTask = function (task) {
            return settings.form_task == task;
        };

        /** Property setter, accepts parameters property, value
         * property can be string (plugin property name) or
         *  object structured like {property_name: property_value, ....}
         *
         */
        this.setProperty = function (property, value) {
            if (typeof property == 'string') {
                setProp(property, value);
            } else {
                for (prop in property) {
                    setProp(prop, property[prop]);
                }
            }
            return _this;
        };
        /* Open modal */
        this.openModal = function (entityId = null, data) {
            let modal = settings.modal_selector;
            if(entityId){
                _this.getOneEntity({
                    'entityId': entityId
                }).setProperty('form_task', 'update');
            } else {
                _this.setProperty('form_task', 'create');
            }
            formHendler(data);
            modal.modal('show');
            return _this;
        };
        /* Close modal */
        this.closeModal = function (data) {
            let modal = settings.modal_selector;
            modal.modal('hide');
            return _this;
        };

        /* get one entity trough ajax */
        this.getOneEntity = function (data, executableFunc = false) {
            $.ajax({
                url: settings.ajax_getOne,
                type: 'GET',
                async: false,
                data: $.extend({}, data),
                success: function (response) {
                    if (settings.form_fill_on_ajax) {
                        fillForm(response.data);
                    }
                    if (_this._ongetoneentity != undefined) {
                        _this._ongetoneentity(response);
                    } else {
                        if(executableFunc){
                            ifClosureExec(executableFunc(response));
                        }
                    }
                }
            });
            return _this;
        };

        /* get all entity trough ajax */
        this.getAllEntity = function (data) {
            return _this;
        };
        /* create entity in db */
        this.createEntity = function (data) {
            if (settings.ajax_use) {
                if (settings.ajax_create != '' && settings.form_selector != null) {
                    $.ajax({
                        url: settings.ajax_create,
                        type: 'post',
                        data: settings.form_selector.serialize(),
                        success: function (response) {
                            if (_this._onsave != undefined) {
                                _this._onsave(response.data);
                            } else {
                                // default akcije
                            }
                            _this.closeModal();
                        }
                    });
                } else {
                    console.error('Create route not defined or form undefiend');
                }
            } else {
                if (_this._onsave != undefined) {
                    _this._onsave(response = '');
                } else {
                    console.log('Error');
                }
                _this.closeModal();
            }

            return _this;
        };
        /* update entity in db */
        this.updateEntity = function (data) {
            if (settings.ajax_use) {
                if (settings.ajax_update != '' && settings.form_selector != null) {
                    $.ajax({
                        url: settings.ajax_update,
                        type: 'post',
                        data: settings.form_selector.serialize(),
                        success: function (response) {
                            if (_this._onsave != undefined) {
                                _this._onsave(response.data);
                            } else {
                                // default akcije
                            }
                            _this.closeModal();
                        }
                    });
                } else {
                    console.error('Create route not defined or form undefiend');
                }
            } else {
                if (_this._onsave != undefined) {
                    _this._onsave(response = '');
                } else {
                    // default akcije
                }
                _this.closeModal();
            }
            return _this;
        };
        /* delete entity in db */
        this.deleteEntity = function (data) {
            if (settings.ajax_use) {

            } else {
                if (_this._onsave != undefined) {
                    _this._onsave(response = '');
                } else {
                    // default akcije
                }
                _this.closeModal();
            }
            return _this;
        };
        /* Parse html that will be injected in editor */
        this.parseEditorHtml = function (data) {

            return _this;
        };

        this.onSaveEntity = function (data) {
            _this._onsave = data;
            return _this;
        };
        this.onCloseModal = function (data) {
            _this._onclosemodal = data;
            return _this;
        };
        this.onGetOneEntity = function (data) {
            _this._ongetoneentity = data;
            return _this;
        }
        this.getSettings = function () {
            return settings;
        };
        return this.init(options);
    };
})(jQuery);