<template>
    <div :class="bem({ debug })">
        <div v-if="measuring || true" ref="container" :class="[bem('container'), containerClass]">
            <div ref="content" :class="bem('content')">
                <slot />
            </div>
        </div>
    </div>
</template>

<script>
import PxBaseResize from '../bases/PxBaseResize.vue';

/**
 * This seems to be pretty purpose built right now and needs to be updated so that it can be used in
 * a more general way. Only responds to width changes and the usage seems to require a specific
 * structure that isn't obvious. Look for usage in one of the chat components.
 */
export default {
    name: 'px-measure-container',
    // components: { Component },
    mixins: [PxBaseResize],
    props: {
        debug: { type: Boolean, default: false },
        containerClass: { type: String, default: null },
        autoUpdate: { type: Boolean, default: true },

        // a delay inserted after the content has been hydrated and before measuring the size, if another update
        // occurs during the delay, the previous update will be cancelled
        delay: { type: Number, default: 50 },
    },
    data() {
        return { measuring: false, size: { width: 0, height: 0 } };
    },

    methods: {
        resize() {
            if (this.autoUpdate) {
                this.update();
            }
        },
        update(onComplete) {
            if (this.timeout) {
                clearTimeout(this.timeout);
            }

            this.measuring = true;

            this.timeout = setTimeout(() => {
                this.$emit('measure', this.$refs.content);

                const size = {
                    width: this.$refs.content.offsetWidth,
                    height: this.$refs.content.offsetHeight,
                };
                this.size = size;

                if (onComplete) {
                    onComplete(size);
                }

                this.$emit('update', size);

                this.measuring = false;
            }, this.delay);
        },
    },
};
</script>

<style lang="scss">
.px-measure-container {
    opacity: 0;
    pointer-events: none;
    position: absolute;
    width: 100%;
    top: 0;
    left: 0;

    &--debug {
        opacity: 1;
        border: 1px dashed red;
    }

    &__container {
        position: absolute;
        width: 100%;
    }

    &__content {
        position: relative;
    }
}
</style>
