import nav from './config/navigation'

export const randomID6n = () => Math.floor(100000 + Math.random() * 900000)

const getNavProperty = (route, prop, placeholder) =>{
  try{
    return nav.routes.filter(r => r.slug === route)[0][prop]
  }catch (e) {
    return placeholder
  }
}

export const ___fetchFilter = route => {
  return  route === 'all' ? null : route === 'archive'
}
export const ___fetchLimit = route => {
  return getNavProperty(route, 'fetchLimit', window.env.prePopulateAmount)
}

export const ___template = route => {
  return getNavProperty(route, 'template', nav.template)
}

export const ___route = route => {
  return getNavProperty(route, 'slug', nav.initialTab)
}

/**
 *
 * @param date
 * @returns {string}
 */
export const ___formatDate = date => {
  const dt = new Date(date)
  return [ window.env.lists.monthsFull[dt.getMonth()], dt.getDate(), `, ${dt.getFullYear()}`].join(' ')
}

/**
 *
 * @param string
 * @returns {string}
 */
export const ___ucWords = string => {
  return string.split('_').map(word => word.charAt(0).toUpperCase() + word.substr(1).toLowerCase()).join(' ')
}

/**
 *
 * @param str
 * @returns {*[]}
 */
export const ___findDates = str => {
  const dates = []
  const regex = new RegExp('[0-3]?[0-9].[0-3]?[0-9].(?:[0-9]{2})?[0-9]{2}', 'mg')

  for (const match of (str || '').matchAll(regex)) {
    dates.push(match[0])
  }

  return dates
}


export const ___set404 = (set = false,  sleep = 5000) => {
  if( set === false ) return

  document.body.innerHTML = `<div class="uk-container uk-text-center">
    <div class="uk-container">
        <ul id="asSwitcher"
        class="uk-subnav uk-subnav-divider uk-margin-large-bottom uk-flex-center">
            <li class="nav-tab"><a href="/all">All Notes</a></li>
            <li class="nav-tab initial uk-active"><a href="/">Recent Notes</a></li>
            <li class="nav-tab"><a href="/archive">Archived Notes</a></li>
            <li class="nav-tab"><a href="/analytics">Analytics</a></li>
        </ul>
    </div>
    
    <h1 class=" uk-text-danger">404 - NOT FOUND</h1>
    <div class="uk-text-large uk-text-muted uk-text-bold">U will be redirected soon</div>
    
</div>`
  setTimeout( () => {
    window.location.assign('/')
  }, sleep)
}


 /**
  *
  * @param $form
  * @param data
  */
 export const ___fillTheForm = ( $form, data ) => {

  if ($form instanceof Node) {

    if (data.length === 1) {
      for (const [key, value] of Object.entries(data[0])) {
        const $input = $form.querySelector(`[name='${key}']`)

        if ($input instanceof Element) {

          if ($input.type === 'checkbox') {

            if (value !== '') {
              $input.click()
            }

          } else {
            $input.value = value
          }
        }
      }
    }
  }
}