import { apiEndpoints } from './store'


/*
** Debounce function with a delay
** (For scrolling or other resource demanding behaviors)
*/
export const debounce = (callback, wait, immediate = false) => {
    let timeout = null
    return function () {
        const callNow = immediate && !timeout
        const next = () => callback.apply(this, arguments)
        clearTimeout(timeout)
        timeout = setTimeout(next, wait)
        if (callNow) next()
    }
}


/*
** Throttle function with a delay
** (Throttling enforces a maximum number of times a function can be called over time, as in 'execute this function at most once every 100 milliseconds)
*/
export function throttle (fn, delay) {
    let lastCall = 0
    return function (...args) {
        const now = (new Date).getTime()
        if (now - lastCall < delay) return
        lastCall = now
        return fn(...args)
    }
}


/*
** Wrap string's each letters into a span
*/
export const lettersToSpan = string => {
    return string
        .replace(/(<.*?>)|(.)/g, letter => letter.replace(/./g, '<span>$&</span>'))
        .replace(/ /g, '\u00a0')
}


/*
** Check if element is in viewport
*/
export const isInViewport = element => {
    const bounding = element.getBoundingClientRect()
    return (
        bounding.top >= 0 &&
        bounding.left >= 0 &&
        bounding.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
        bounding.right <= (window.innerWidth || document.documentElement.clientWidth)
    )
}



/*
** Smooth Scroll
*/
export const smoothScroll = (event, element = null) => {
    document.querySelector(element).scrollIntoView({
        behavior: 'smooth',
        block: 'start'
    })
    event.preventDefault()
}



/*
** Random String Generator
*/
export const randomString = (length = 6, type = 'A') => {
    type = type && type.toLowerCase()
    let str = ''
    let i = 0
    const min = type == 'a' ? 10 : 0
    const max = type == 'n' ? 10 : 62
    for (; i++ < length;) {
        let r = Math.random() * (max - min) + min << 0
        str += String.fromCharCode(r += r > 9 ? r < 36 ? 55 : 61 : 48)
    }
    return str
}


/*
** Get thumbnail from API
*/
export const getThumbnail = (id, width, height, type = 'crop', quality = 75) => {
    const ratio = 1.5
    height = !height ? Math.round(width / ratio) : height
    return `${apiEndpoints.rest}/assets/${id}?w=${width}&h=${height}&f=${type}&q=${quality}`
}
