const Prism = require('prismjs')

require('prismjs/plugins/line-numbers/prism-line-numbers.css')
require('prismjs/themes/prism-twilight.css')

require('prismjs/components/prism-scss')
require('prismjs/components/prism-markup')
require('prismjs/components/prism-markup-templating')
require('prismjs/components/prism-css')
require('prismjs/components/prism-clike')
require('prismjs/components/prism-javascript')
require('prismjs/components/prism-bash')
require('prismjs/components/prism-markdown')
require('prismjs/components/prism-nginx')
require('prismjs/components/prism-php')
require('prismjs/components/prism-python')
require('prismjs/components/prism-sql')
require('prismjs/components/prism-yaml')
require('prismjs/components/prism-twig')
require('prismjs/components/prism-shell-session')

require('prismjs/plugins/keep-markup/prism-keep-markup')
require('prismjs/plugins/line-highlight/prism-line-highlight')
require('prismjs/plugins/line-numbers/prism-line-numbers')

class Code {
    constructor(w) {
        this.window = w
    }

    init() {
        Prism.highlightAllUnder(document)
        let elements = this.window.document.querySelectorAll('code[data-title], div[data-title]')

        for (let i = 0, len = elements.length; i < len; i++) {
            const element = elements[i]

            if (element.tagName === 'CODE') {
                var code = element
                var pre = code.parentNode
                var post = pre.parentNode
            } else {
                var code = element.querySelector('code')

                if (!code) {
                    continue
                }

                var pre = code.parentNode
                var post = pre.parentNode
            }

            if (!pre || !post) {
                continue
            }

            pre.classList.add('with-title')

            const title = this.window.document.createElement('div')
            title.classList.add('code-title')
            title.textContent = element.getAttribute('data-title')

            post.insertBefore(title, pre)
        }

        elements = this.window.document.querySelectorAll('code.window')

        for (let i = 0, len = elements.length; i < len; i++) {
            const element = elements[i]

            if (element.tagName === 'CODE') {
                var code = element
                var pre = code.parentNode
                var post = pre.parentNode
            } else {
                var code = element.querySelector('code')

                if (!code) {
                    continue
                }

                var pre = code.parentNode
                var post = pre.parentNode
            }

            if (!pre || !post) {
                continue
            }

            pre.classList.add('with-title')
            const win = this.window.document.createElement('div')
            win.classList.add('code-window')

            post.insertBefore(win, pre)
        }
    }
}

module.exports = Code
