/*
 * Bellamy
 * CommonJS module
 */

// Overlay
function overlay () {
  let e = document.querySelectorAll('html > body')
  Array.prototype.forEach.call(e, function (item) {
    item.insertAdjacentHTML('afterbegin', '<div class="w3-overlay w3-hide" style="cursor:pointer;top:45pt" id="overlay"></div>')
  })
  addClasses('#overlay', ['w3-animate-opacity'])
  e = document.getElementById('overlay')
  e.addEventListener('click', function (e) {
    window.sidebar()
  }, false)
}

// Add CSS classes to item
function addClasses (selector, classes) {
  const e = document.querySelectorAll(selector)
  Array.prototype.forEach.call(e, function (item) {
    Array.prototype.forEach.call(classes, function (c) {
      item.classList.add(c)
    })
  })
}

// Add Font Awesome SVG icon
function addIcon (selector, icon) {
  const e = document.querySelectorAll(selector)
  Array.prototype.forEach.call(e, function (item) {
    if (item.textContent.length > 0) {
      item.classList.add('normal-font')
      item.insertAdjacentHTML('afterbegin', `<i style="margin-right:5pt" class="fa-solid ${icon}"></i>`)
    }
  })
}

// Header
function header () {
  let logo = ''
  let text = ''
  let description = ''

  let e = document.querySelectorAll('#block-bellamy-branding a img')
  Array.prototype.forEach.call(e, function (item) {
    logo = item.src.trim()
  })

  e = document.querySelectorAll('#block-bellamy-branding a')
  Array.prototype.forEach.call(e, function (item) {
    if (item.textContent.length > 0) {
      text = item.textContent.replace(/[\n\r]/g, '')
      text = text.trim()
    }
  })

  e = document.querySelectorAll('#block-bellamy-branding')
  Array.prototype.forEach.call(e, function (item) {
    if (item.textContent.length > 0) {
      description = item.textContent.replace(/[\n\r]/g, '').trim()
      description = description.replace(text, '').trim()
    }
  })

  const header = `<!-- Bellamy - header -->
    <!-- Logo -->
    <a href="/">
      <div id="logo" class="w3-display-topleft w3-padding-large">
        <img alt="Home" style="height:28pt;margin-right:10pt;vertical-align:bottom" src="${logo}"></img>
        <span style="text-decoration:none" class="w3-hide-small">${text}</span>
      </div>
    </a>
    <!-- Site description -->
    <div id="description" class="w3-display-topmiddle w3-padding-large w3-hide-small w3-hide-medium">
      <i class="fa-solid fa-minus w3-text-light-grey" style="vertical-align:-3pt"></i>
      ${description}
      <i class="fa-solid fa-minus w3-text-light-grey" style="vertical-align:-3pt"></i>
    </div>
    <!-- Bar -->
    <div id="menu" class="w3-display-topright w3-bar w3-white w3-xlarge" style="width:auto;height:45pt;overflow:hidden">
      <!-- User -->
      <a href="/user">
        <div id="user" style="width:45pt;padding:10pt 0" class="w3-hover-white w3-bar-item w3-button">
          <i class="fa-solid fa-user-circle"></i>
        </div>
      </a>
      <!--  Search -->
      <a href="/search">
        <div id="search" style="width:45pt;padding:10pt 0" class="w3-hover-white w3-bar-item w3-button">
          <i class="fa-solid fa-search"></i>
        </div>
      </a>
      <!-- Hamburger -->
      <div id="hamburger" onclick="sidebar()" style="width:45pt;padding:10pt 0" class="w3-hover-white w3-bar-item w3-button">
        <i class="fa-solid fa-bars"></i>
      </div>
    </div>`

  e = document.querySelectorAll('.layout-container header > div')
  Array.prototype.forEach.call(e, function (item) {
    if (item.textContent.length > 0) {
      item.insertAdjacentHTML('afterbegin', header)
    }
  })
}

// Footer
function footer () {
  let m = ''
  let text = ''
  let e = document.querySelectorAll('#block-bellamy-footer ul > li > a')
  Array.prototype.forEach.call(e, function (item) {
    if (item.textContent.length > 0) {
      m = m.concat('<a style="min-height:45pt!important;padding:14pt 18pt" class="w3-button w3-hover-black" href="', item.href, '">', item.textContent, '</a>')
    }
  })

  e = document.querySelectorAll('#block-bellamy-powered')
  Array.prototype.forEach.call(e, function (item) {
    if (item.textContent.length > 0) {
      text = 'Powered by Drupal'
    }
  })

  const footer = `<!-- Bellamy - footer -->
  <div class="w3-highway-red w3-center">
    <div class="w3-highway-red w3-mobile w3-left w3-hide-small">
      <a style="min-height:45pt!important;padding:14pt 18pt" class="w3-hover-black w3-button" target="blank" href="https://www.drupal.org" title="Powered by Drupal">${text}</a>
    </div>
    <div class="w3-highway-red w3-mobile w3-right">${m}</div>
  </div>`

  e = document.querySelectorAll('.layout-container > footer > div')
  Array.prototype.forEach.call(e, function (item) {
    if (item.textContent.length > 0) {
      item.insertAdjacentHTML('afterbegin', footer)
    }
  })
}

// Comments
function comments () {
  let picture = ''
  let title = ''
  let text = ''
  let links = ''
  let author = ''
  let user = ''

  const e = document.querySelectorAll('main [typeof="schema:Comment"]')
  Array.prototype.forEach.call(e, function (item) {
    let c = item.querySelectorAll('article > div > h3')
    Array.prototype.forEach.call(c, function (str) {
      title = str.textContent.trim()
    })

    c = item.querySelectorAll('article > div > div')
    Array.prototype.forEach.call(c, function (str) {
      text = str.outerHTML.trim()
    })

    c = item.querySelectorAll('article > div > ul')
    Array.prototype.forEach.call(c, function (str) {
      links = str.outerHTML.trim()
    })

    c = item.querySelectorAll('footer > article > div > a > img')
    Array.prototype.forEach.call(c, function (str) {
      picture = str.src.trim()
    })

    c = item.querySelectorAll('footer [rel="schema:author"] > a, footer [rel="schema:author"] > span')
    Array.prototype.forEach.call(c, function (str) {
      if (str.textContent.length > 0) {
        user = str.textContent.trim()
      }
    })

    c = item.querySelectorAll('footer [rel="schema:author"]')
    Array.prototype.forEach.call(c, function (str) {
      if (str.textContent.length > 0 && str.textContent.includes(user)) {
        author = str.textContent.replace(`${user}`, `<br><b>${user}</b><br>`).trim()
      }
    })

    const comment = `<!-- Bellamy - comment -->
      <div class='w3-cell-row w3-padding-16'>
        <div class='w3-cell w3-cell-middle'>
          <div>
            <p class='w3-large w3-text-darkgrey' style='line-height:1.1;padding-bottom:6pt'>
              <i class='fa-solid fa-caret-right'></i> ${title}
            </p>
            ${text}
          </div>
          <div class='w3-text-grey'>${links}</div>
        </div>
        <div class='w3-cell w3-cell-middle w3-center' style='width:130pt'>
          <div class='w3-circle' style='margin:3pt auto;background-image:url(${picture});background-size:cover;background-position:50%;height:30pt;width:30pt'></div>
          <div class='w3-text-grey w3-small' style='white-space:nowrap'>${author}</div>
        </div>
      </div>`

    item.insertAdjacentHTML('beforebegin', comment)
    item.remove()
  })
}

// Sidebar (show/hide)
window.sidebar = function () {
  const e = document.querySelectorAll('main > aside > div')
  Array.prototype.forEach.call(e, function (item) {
    if (item.classList.contains('w3-show')) {
      item.classList.remove('w3-show')
      document.getElementById('overlay').classList.remove('w3-show')
    } else {
      item.classList.add('w3-show')
      document.getElementById('overlay').classList.add('w3-show')
    }
  })
}

// CSS setup
function style () {
  // Icons
  const icons = require('./config/icons.json') // FontAwesome icons
  Array.prototype.forEach.call(icons, function (item) {
    addIcon(item.selector, item.icon)
  })
  // W3.CSS
  const w3css = require('./config/w3.css.json') // W3.CSS
  Array.prototype.forEach.call(w3css, function (item) {
    addClasses(item.selector, item.classes)
  })
  // Bellamy
  const bellamy = require('./config/bellamy.json') // Bellamy custom style
  Array.prototype.forEach.call(bellamy, function (item) {
    addClasses(item.selector, item.classes)
  })
}

// Font Awesome setup
function fontAwesome () {
  require('@fortawesome/fontawesome-free/js/all.js')
  const { dom } = require('@fortawesome/fontawesome-svg-core')
  dom.i2svg().then(function () { console.log('Icons have rendered') })
}

module.exports = {
  // Load
  load: function () {
    console.log('Loading user interface...')

    // DOM manipulation
    // Overlay
    overlay()
    // Header
    header()
    // Footer
    footer()
    // Comments
    comments()

    // Style
    style()
    // Font Awesome
    fontAwesome()

    // Loader
    // This must be the last function called
    addClasses('.layout-container', ['no-after', 'visible', 'w3-animate-opacity'])
    console.log('Ready')
  }
}
