import { throttle, debounce } from 'throttle-debounce'

/**
 *  Tiny Masonry
 *
 *  @author Björn Hase
 *  @license http://opensource.org/licenses/MIT The MIT License
 *  @link https://gitea.node001.net/tiny-components/masonry
 *
 */

class Masonry {

    /**
     *
     *
     */
    constructor() {

        // getting elements 
        this.elements = document.querySelectorAll('.tiny-masonry__item-inner')
        this.container = document.querySelector('.tiny-masonry')

        this.calculate()

        window.addEventListener('resize', throttle(300, () => {
            this.calculate()
        }), false)
    }

    /**
     *
     *
     */
    calculate() {

        // getting number of columns 
        this.columns = Math.ceil(this.container.offsetWidth / this.elements[0].parentElement.offsetWidth) - 1

        // reset margin-top
        for (let i = 0; i < this.elements.length; i++) {
            this.elements[i].parentElement.style.marginTop = '0px'
        }

        for (let i = 0; i < this.elements.length; i++) {

            // adding each parent element in column
            if (this.elements[i + this.columns]) {

                let offset = 0

                // if style was already setup adding to offset 
                if (this.elements[i] && this.elements[i].parentElement.style.marginTop) {
                    offset += parseInt(this.elements[i].parentElement.style.marginTop)
                }

                // setting margin top 
                this.elements[i + this.columns].parentElement.style.marginTop = this.elements[i].offsetHeight + parseInt(offset) + 'px'
            }
        }
    }
}

export default Masonry
