
if ( !window.Chorus ) window.Chorus = {}

Chorus.processCommentArray = function(comments) {
    for ( const comment of comments ) {
        comment.date = new Date(comment.date)

        if ( comment.replies ) {
            Chorus.processCommentArray(comment.replies)
        }
    }
}

Chorus.processThreadData = function(threadData) {
    threadData.refresh.date = new Date(threadData.refresh.date)
    Chorus.processCommentArray(threadData.comments)

    threadData.comments = threadData.comments
        .sort((a, b) => b.date.getTime() - a.date.getTime())

    return threadData
};

Chorus.init = async function(selector) {
    const el = document.querySelector(selector)
    if ( !el ) {
        console.warn('[Chorus] Could not init: could not find element with selector: ' + selector)
        return
    }

    let baseUrl = el.getAttribute('data-chorus-url')
    if ( !baseUrl ) {
        console.warn('[Chorus] Could not init: host element is missing data-chorus-url attribute')
        return
    }
    if ( !baseUrl.endsWith('/') ) {
        baseUrl += '/'
    }

    const threadId = el.getAttribute('data-chorus-thread')
    if ( !threadId ) {
        console.warn('[Chorus] Could not init: host element is missing data-chorus-thread attribute')
        return
    }

    const threadDataUrl = `${baseUrl}threads/${threadId}.json`
    const response = await fetch(threadDataUrl)

    if ( response.status === 404 ) {
        await Chorus.render404(el, baseUrl)
        return
    }

    if ( !response.ok ) {
        console.error('[Chorus] Failed to load thread data')
        return
    }

    const threadData = Chorus.processThreadData(await response.json())

    Chorus.renderSummary(el, threadData)

    const commentsDiv = document.createElement('div')
    commentsDiv.classList.add('chorus-comments-list')
    for ( const comment of threadData.comments ) {
        Chorus.renderComment(commentsDiv, comment)
    }

    el.appendChild(commentsDiv)
    console.log(threadData)
};

Chorus.render404 = async function(el, baseUrl) {
    let refreshDate = undefined
    try {
        const rootDataUrl = `${baseUrl}root.json`
        const response = await fetch(rootDataUrl)
        if ( response.ok ) {
            const rootData = await response.json()
            if ( rootData && rootData.refresh && rootData.refresh.date ) {
                const date = new Date(rootData.refresh.date)
                if ( !isNaN(date.getTime()) ) {
                    refreshDate = date
                }
            }
        }
    } catch (e) {
        console.error('[Chorus] Error when loading refresh date from root data', e)
    }

    const summaryDiv = document.createElement('div')
    summaryDiv.classList.add('chorus-summary')
    el.appendChild(summaryDiv)

    const summaryUl = document.createElement('ul')
    summaryDiv.appendChild(summaryUl)

    const countLi = document.createElement('li')
    countLi.innerText = `There are no comments yet.`
    summaryUl.appendChild(countLi)

    if ( refreshDate ) {
        const lastRefreshLi = document.createElement('li')
        lastRefreshLi.innerText = `Last refreshed: ${refreshDate.toLocaleString()}`
        summaryUl.appendChild(lastRefreshLi)
    }
};

Chorus.renderComment = function(commentsDiv, comment) {
    const commentDiv = document.createElement('div')
    commentDiv.classList.add('chorus-comment')
    commentDiv.style.setProperty('--chorus-author-color', comment.user.color)
    commentsDiv.appendChild(commentDiv)

    const bylineEl = document.createElement('div')
    bylineEl.classList.add('chorus-byline')
    commentDiv.appendChild(bylineEl)

    const chipEl = document.createElement('div')
    chipEl.classList.add('chorus-author-chip')
    chipEl.title = 'User ID: ' + comment.user.mailId + '\nDomain ID: ' + comment.user.domainId
    bylineEl.appendChild(chipEl)

    const authorEl = document.createElement('h2')
    authorEl.classList.add('chorus-author')
    authorEl.innerText = comment.user.name
    authorEl.title = 'User ID: ' + comment.user.mailId + '\nDomain ID: ' + comment.user.domainId
    bylineEl.appendChild(authorEl)

    const statusEl = document.createElement('p')
    statusEl.classList.add('chorus-status')
    commentDiv.appendChild(statusEl)

    const dateEl = document.createElement('span')
    dateEl.innerText = comment.date.toLocaleString()
    statusEl.appendChild(dateEl)

    const sepEl = document.createElement('span')
    sepEl.innerText = ' | '
    statusEl.appendChild(sepEl)

    const replyEl = document.createElement('a')
    replyEl.innerText = 'Reply'
    replyEl.href = `mailto:${comment.replyAddress}`
    statusEl.appendChild(replyEl)

    if ( comment.subject ) {
        const subjectEl = document.createElement('h3')
        subjectEl.innerText = comment.subject
        commentDiv.appendChild(subjectEl)
    }

    const contentEl = document.createElement('p')
    contentEl.innerHTML = comment.rendered
    commentDiv.appendChild(contentEl)

    if ( comment.replies && comment.replies.length > 0 ) {
        const repliesDiv = document.createElement('div')
        repliesDiv.classList.add('chorus-replies')
        commentDiv.appendChild(repliesDiv)

        for ( const reply of comment.replies ) {
            Chorus.renderComment(repliesDiv, reply)
        }
    }
};

Chorus.renderSummary = function(el, threadData) {
    const summaryDiv = document.createElement('div')
    summaryDiv.classList.add('chorus-summary')
    el.appendChild(summaryDiv)

    const summaryUl = document.createElement('ul')
    summaryDiv.appendChild(summaryUl)

    const countLi = document.createElement('li')
    countLi.innerText = `${threadData.comments.length} comment${threadData.comments.length === 1 ? '' : 's'}`
    summaryUl.appendChild(countLi)

    const lastRefreshLi = document.createElement('li')
    lastRefreshLi.innerText = `Last refreshed: ${threadData.refresh.date.toLocaleString()}`
    summaryUl.appendChild(lastRefreshLi)
};
