(function (paw, _super) {

    /**
     *  settings {
          blob: Blob,
          url: string,
          recalcHeight: boolean,
          controls: boolean,
          downloadUrl: string,
          previewNotAvailableLabel: string
        }
     * 
     * @param {any} $container
     * @param {any} settings
    */
    paw.lang.extend(DocxComponent, _super);
    function DocxComponent($container, settings) {
        _super.call(this, $container, settings, 'fa fa-file-word-o fa-4x');
    }

    DocxComponent.prototype.renderDocument = function () {
        var d = paw.utils.async.defer();
        docx.renderAsync(this.blob, this.$container.get(0), null, {
            ignoreWidth: true
        }).then(function(res){
            d.resolve(res);
            return res;
        }).catch(function (err) {
            console.error("Could not render docx: " + err);
            d.reject(err);
        });
        return d.promise;
    };

    DocxComponent.prototype.compilePreview = function () {
        let $docWrapper = this.$container.find('.docx-wrapper');
        $docWrapper.css('margin-top', '');
        $docWrapper.css('transform', '');

        if ($docWrapper.length === 0) {
            return;
        }

        let $doc = $docWrapper.find('.docx');
        let containerW = this.$container.width();
        let docW = $doc.outerWidth();
        if (docW === 0) {
            return;
        }
        // calculate scale (delta) to fit document into the container
        // move doc wrapper for it's original offset and scalled offset top,
        // to align it on top - otherwise it stays on center of it's original position (flex box)
        let delta = containerW / docW;
        let wrapperOffsetTop = $docWrapper.position().top;
        this.$container.parent().css({
            'background-color': $docWrapper.css('background-color')
        });
        $docWrapper.css({
            transform: 'scale(' + delta + ')'
        });

        let offsetTop = $docWrapper.position().top + wrapperOffsetTop;
        $docWrapper.css({
            'margin-top': -offsetTop
        });

        // recalculate height, when needed (container has dynamic height)
        if (this.settings.recalcHeight) {
            this.$container.height($docWrapper.outerHeight() - offsetTop);
        }
    };

	paw.com.DocxComponent = DocxComponent;
})(paw, paw.com.DocumentViewerComponent);