const Centerable = (($)=> {
    const DefaultConfig = {
        dragHandle: null,      
        stopHandle: null       
    }
    class Centerable {
        constructor(config) {
            this._config = this._getConfig(config);
            this._$target = $(this._config.target);
            if(this._config.wrap){
                this._$wrap = $(this._config.wrap);
            }
            else{
                this._$wrap = $(window);
            }
            this._$wrap.bind('resize', ()=> {
                this.center();
            });
            this._$wrap.bind('scroll', ()=>{
                this.center();
            });
        }
        
        _getConfig(config) {
            return $.extend(true, {}, DefaultConfig, config);
        }
        center = function(loaded) {
            var obj = this._$target;
            if(obj){
                let $wrap = this._$wrap;
                let body_width = parseInt($wrap.width());
                let body_height = parseInt($wrap.height());
                let block_width = parseInt(obj.width());
                let block_height = parseInt(obj.height());
                let scrollLeft = $wrap.scrollLeft();
                let scrollTop = $wrap.scrollTop();
                let left_position = parseInt((body_width - block_width) * 0.5 + scrollLeft);
                if (body_width < block_width) {
                    left_position = scrollLeft;
                }
                let top_position = parseInt((body_height - block_height) * 0.5 + scrollTop);
                if (body_height < block_height) {
                    top_position = scrollTop;
                }
                if (!loaded) {
                    obj.css({
                        'position': 'absolute'
                    });
                    obj.css({
                        'top': (body_height - block_height) * 0.5,
                        'left': left_position
                    });
                }
                else {
                    obj.css({
                        'position': 'absolute'
                    });
                    obj.css({
                        'top': top_position,
                        'left': left_position
                    });
                }
            }
        }
        dispose(){
            if(this._$wrap){
                this._$wrap.unbind("resize");
                this._$wrap.unbind("scroll");
                this._$wrap = null;
            }
            if(this._$target){
                this._$target = null;
            }
            this._config = null;
        }
    }
    return Centerable;
})($);
export default Centerable;