var CsAsset = function(){

    var CsAsset = function(type){

        this.absoluteUrl = 0;
        this.type  = type;
        this.asset = this.createAsset();
        this.modal = {
            id: 'cs-image-modal',
            html: '',
            options: {},
            searchInput: {},
            resultsContainer: {}
        };

        this.callBack = {};
    };

    CsAsset.prototype.createAsset = function(id) {
        return  {
            id: this.asset ? this.asset.id : '',
            src: '',
            title: '',
            type: this.type,
            embed: '',
            resize: this.asset ? this.asset.resize : null,
            poster: '',
            html: '',
            width: 0,
            height: 0
        };
    };

    CsAsset.prototype.exec = function(asset,callBack) {

        var _this = this;

        this.callBack = callBack;

        this.asset = asset;

        this.signals.onModalContentLoaded.add(function() {
            _this.bindFunctions();
            $('body').addClass('modal-open-noscroll');

            if (_this.asset.id) {
                _this.buildCrops();
            }
        });

        this.signals.onDestroyModal.add(function() {
            _this.reset();
            $('body').removeClass('modal-open-noscroll');
        });

        this.showModal();
    };

    CsAsset.prototype.createModal = function(callBack) {
        var _this = this;

        this.modal.html  = $('<div></div>')
            .attr({
                "id":this.modal.id,
                "class": 'modal fade bs-modal-lg',
                "tabindex": "-1",
                "role": "dialog",
                "aria-labelledby": "myModalLabel1",
                "aria-hidden": "true"
            })
            .load(Routing.generate('designer_ck_asset_modal', { asset:_this.asset, type: _this.type }), function(){
                _this.signals.onModalContentLoaded.dispatch();
            })
            .modal({
                show: false
            });

        $('body').append(this.modal.html);

        this.modal.html.on('hidden.bs.modal', function () {
            _this.destroyModal();
        });

        this.signals.onModalCreated.dispatch();

        callBack.call(this,this);
    };

    CsAsset.prototype.destroyModal = function() {
        this.signals.onDestroyModal.dispatch();
    };

    CsAsset.prototype.showModal = function() {

        this.createModal(function(){
            this.modal.html.modal().show();
        });
    };

    CsAsset.prototype.hideModal = function() {
        this.modal.html.modal('hide');
    };

    CsAsset.prototype.bindFunctions = function() {
        var _this = this;

        AssetsHelper.initWidget("#" + this.modal.id);

        AssetsHelper.signals.onLibraryAdd.add(function(parent, origObject, destObject){
            var assetId = destObject.data("id-content");
            _this.fetchAssetData(assetId);
            _this.modal.html.find('#submit').attr('disabled', false);
        });

        _this.modal.html.find('[data-action="unselect"]').on("click", function(){
            _this.resetAsset();
        });

        AssetsHelper.signals.onLibraryRemove.add(function(){
            _this.resetAsset();
        });

        AssetsHelper.signals.onNewAfterRemove.add(function(){
            _this.resetAsset();
        });

        AssetsHelper.signals.onNewCreate.add(function(response) {
            _this.fetchAssetData(response.metadata.id);
            _this.modal.html.find('#submit').attr('disabled', false);
        });

        this.modal.html.on('click', '#submit', function(){
            var title = _this.modal.html.find('[data-entity="title"]').val();

            if (title) {
                _this.asset.title = title;
            }
            _this.sendCallBack();
        });

        $(window).on('cs:assetsEditClose', function() {
            _this.modal.html.find('#submit').attr('disabled', true);
            setTimeout(function() {
                _this.fetchAssetData(_this.asset.id);
                _this.modal.html.find('#submit').attr('disabled', false);
            }, 1500);
        })
    };

    CsAsset.prototype.resetAsset = function() {
        this.asset.id = null;
        this.asset.resize = null;
    };

    CsAsset.prototype.buildCrops = function() {
        var _this = this;

        if (_this.asset.type === "image") {
            var _modal = $(this.modal.html);
            var _cropsContainer = $('<div class="asset-crops">'+Translator.trans('cs_assets.ckeditor_modal.crops.loading')+'</div>');

            /**
             * Prevent to add duplacations. If crops block already exists do nothing
             */
            if (_modal.find(".asset-crops").length > 0) {
                return;
            }

            _modal.find(".input-icon").after(_cropsContainer);

            _cropsContainer.load(
                Routing.generate('designer_ck_asset_crops_template', { id: _this.asset.id, resize: _this.asset.resize }), {
                    absoluteUrl: _this.absoluteUrl
                },
                function(){
                    var resizeEl = _cropsContainer.find("[data-resize]");
                    var original = _cropsContainer.find("#original");

                    resizeEl.on("click", function(e, options){
                        var setResize = true;
                        var fromLoad = typeof options != "undefined" ? options.fromLoad : false;

                        if ($(this).hasClass("active") && !fromLoad) {
                            setResize = false;
                        }

                        _cropsContainer
                            .find("[data-resize]")
                            .removeClass('active');

                        if (setResize) {
                            $(this).addClass("active");
                            _this.asset.src = $(this).data("src");
                            _this.asset.resize = $(this).data("resize");
                            _this.asset.width = $(this).data("width");
                            _this.asset.height = $(this).data("height");
                        } else {
                            _this.asset.src    = original.data("original");
                            _this.asset.height = original.data("original-height");
                            _this.asset.width  = original.data("original-width");
                            _this.asset.resize = null;
                        }
                    });

                resizeEl.each(function(){
                    if ($(this).hasClass("active")) {
                        $(this).trigger("click", {fromLoad:true});
                    }
                });
            });
        }

    };

    CsAsset.prototype.fetchAssetData = function(id) {
        var _this = this;

        $.ajax({
            url: Routing.generate('designer_ck_asset_fetch', { id: id}),
            async:false,
            method: 'post',
            data: {
                absoluteUrl: _this.absoluteUrl
            },
            success: function(response) {
                _this.asset.src   = response.url;
                _this.asset.title = response.title;
                _this.asset.embed = response.embed;
                _this.asset.id    = id;
                _this.asset.poster = response.poster;
                _this.asset.html = response.html;
                _this.asset.width = response.width;
                _this.asset.height = response.height;

                _this.buildCrops();
            }
        });
    };

    CsAsset.prototype.reset = function() {
        var _this = this;

        $("#" + this.modal.id).remove();

        $.each(_this.signals, function(k,v){
            v.removeAll();
        });

        AssetsHelper.signals.onLibraryAdd.removeAll();
        AssetsHelper.signals.onNewCreate.removeAll();

    };

    CsAsset.prototype.sendCallBack = function() {
        if ( typeof this.callBack === 'function') {
            this.hideModal();
            this.callBack.call(this,this);
        }
    };

    CsAsset.prototype.signals = {
        onModalCreated: new signals.Signal(),
        onDestroyModal: new signals.Signal(),
        onModalContentLoaded: new signals.Signal()
    };

    CsAsset.prototype.setAbsoluteUrl = function(absolute) {
        this.absoluteUrl = Number(absolute);
    };

    CsAsset.prototype.setAbsoluteUrlFromCKEditor = function(editor) {
        var absolute = 0;

        if (editor.config.csAsset && editor.config.csAsset.absoluteUrl) {
            absolute = editor.config.csAsset.absoluteUrl;
        } else if(editor.element.$.getAttribute("data-cs-asset-absolute-url")) {
            absolute = editor.element.$.getAttribute("data-cs-asset-absolute-url")
        }

        this.setAbsoluteUrl(absolute);
    };

    return {
        init: function(type) {
            return new CsAsset(type);
        }
    };
}();
