export default function List(view, element) {

    view.element = element
    view.cursor = 0
    
    const Render = this.Render = (entries, iResetCursorTo = view.cursor) => {
        while (view.element.firstChild) {
            view.element.removeChild(view.element.lastChild)
        }
        entries.map(renderEntry).forEach(n => view.element.appendChild(n))
        Focus(iResetCursorTo)
    }
    
    const renderEntry = (entry, i) => {
        let ele = document.createElement('li')
    
        if(entry.entries) {
            populateListEntry(entry, ele, i)
        } else {
            populateTrackEntry(entry, ele, i)
        }

        // ele.addEventListener('mouseenter', (event) => {
        //     console.log(event)
        //     if(event.movementX || event.movementY)
        //         Focus(i, false)
        // })

        return ele
    }
    
    const populateListEntry = (entry, ele) => {
        let a = document.createElement('a')
        let header = document.createElement('header')
    
        header.innerText = entry.name
        a.appendChild(header)
        ele.appendChild(a)
    }
    
    const populateTrackEntry = (entry, ele) => {
        // TODO: fix button problem on kaios
        let sect = document.createElement('section')
    
        let trackNumber = document.createElement('code')
        let title = document.createElement('b')
        let artist = document.createElement('cite')

        trackNumber.innerText = formatTrackNumber(entry.trackNumber)
        title.innerText = entry.name
        artist.innerText = entry.artist

        sect.appendChild(title)
        sect.appendChild(artist)

        ele.appendChild(trackNumber)
        ele.appendChild(sect)
    }

    const formatTrackNumber = trackNumber => {
        return trackNumber == Infinity ? '--' : trackNumber.toString().padStart(2, '0')
    }
    
    const Scroll = this.Scroll = (distance) => {
        let children = Array.from(view.element.children)
        let i = view.cursor
        i += distance
        if(i >= children.length) {
            i = 0
        } else if(i < 0) {
            i = children.length - 1
        }
    
        Focus(i)
    }
    
    const Focus = this.Focus = (i, scroll = true) => {
        view.cursor = i
        if(view.element.children.length === 0) {
            return
        }
        if(view.focus) {
            view.focus.classList.remove('focus')
        }
        view.focus = view.element.children[view.cursor]
        view.focus.classList.add('focus')
        if(scroll) {
            view.element.children[Math.max(i - 4, 0)].scrollIntoView()
        }
    }

    const OnKeydown = this.OnKeydown = (event) => {
        switch(event.key) {
            case 'ArrowDown':
                Scroll(1)
                break

            case 'ArrowUp':
                Scroll(-1)
                break

            default:
                return true
        }
    }

    return this
}