import ScrollHelper from "./ScrollHelper";

export default function () {
    return {
        _resolveOutline(doc) {
            var outline = doc.querySelector('.brick-edit-bar-outline');
            if (outline === null) {
                outline = this._createBoundsEl(doc);
            }

            return outline;
        },
        _createBoundsEl(doc) {
            if (typeof doc === 'undefined' || typeof doc.body === 'undefined') {
                return null;
            }

            var outline = doc.createElement('div');

            outline.classList.add('brick-edit-bar-outline');
            outline.style.position = 'absolute';
            outline.style.zIndex = '999';
            outline.style.border = '5px solid rgba(78,115,223,.25)';
            outline.style.background = 'rgba(78,115,223,.25)';
            outline.style.touchAction = 'none';
            outline.style.pointerEvents = 'none';
            outline.style.borderRadius = '5px';

            doc.body.appendChild(outline);

            return outline;
        },
        hide(iframe, bounds) {
            if (typeof iframe === 'undefined') {
                return;
            }
            var doc = iframe.contentWindow.document;
            var outline = this._resolveOutline(doc)

            outline.style.display = 'none';
        },
        draw(iframe, boundsEl) {
            if (typeof iframe === 'undefined') {
                return;
            }
            var doc = iframe.contentWindow.document;
            var outline = this._resolveOutline(doc);
            outline.style.display = 'block';

            var bodyRect = doc.body.getBoundingClientRect();
            var bounds = boundsEl.getBoundingClientRect();
            var iframeScrollTop = ScrollHelper.getScrollTop(doc);

            var offset = {
                // top: bounds.top - bodyRect.top,
                // left: bounds.left - bodyRect.left,
                top: bounds.top,
                left: bounds.left,
            };
            // var barStyle = bar.style;
            // barStyle.top = offset.top - 40 + 'px';
            // barStyle.left = offset.left - 5/* border width */ + 'px';

            var outlineBounds = {
                top: offset.top - 5,
                left: offset.left - 5,
                height: bounds.height + 10,
                width: bounds.width + 10,
            };

            var outlineStyle = outline.style;
            outlineStyle.top = outlineBounds.top + iframeScrollTop + 'px';
            outlineStyle.left = outlineBounds.left + 'px';
            outlineStyle.height = outlineBounds.height + 'px';
            outlineStyle.width = outlineBounds.width + 'px';

            return outlineBounds;
        },
    }
};