import {$id, $class, $query, $create, ajax} from '../utils'
import {startLoading, endLoading} from '../loader'
replyTag = $id 'reply'
reply = null
class Comments
constructor: (@container, sliders) ->
if sliders
spinner = $query '.loader__spinner_comments'
startLoading spinner
form = $id 'comment-form'
@getComments spinner
# Stop replying to comment when the reply tag is clicked
replyTag.addEventListener 'click', ->
reply = null
replyTag.classList.add 'comment-form__reply_hidden'
return
# TODO: Think of a way to not need this
textInput = $id 'comment-text'
textInput.addEventListener 'focus', ->
textInput.parentNode.parentNode.style.borderColor = '#333'
return
textInput.addEventListener 'blur', ->
textInput.parentNode.parentNode.style.borderColor = 'transparent'
return
# Prevent pasting HTML
textInput.onpaste = (e) ->
do e.preventDefault
document.execCommand 'inserttext', false, e.clipboardData.getData 'text/plain'
form.addEventListener 'submit', (e) ->
do e.preventDefault
ajax 'POST', form.action, JSON.stringify(
name: $id('comment-name').value
text: $id('comment-text').innerHTML.replace(/<\/div>|<br\/?>/g, '').replace(/<div>/g, '\n')
reply: reply
), (data) ->
do location.reload
, (error) ->
alert error.response
getComments: (spinner) =>
threads = $id 'comments'
ajax 'GET', 'https://aya.volk.pt/comments', null, (data) ->
comments = JSON.parse data
for comment in comments
# Create thread
thread = $create 'div'
thread.className = 'thread'
thread.id = "thread-#{comment.id}"
# Create comment
div = $create 'div'
div.className = 'comment'
div.dataset.id = "comments-#{comment.id}"
date = new Date parseInt comment.time
day = do date.getDate
month = do date.getMonth + 1
year = do date.getFullYear - 2000
div.innerHTML = "<div><span class='comment__name' style='color: #{comment.color}'>#{comment.name || 'Anonymous'}</span> <span class='comment__date' title='#{date}'>#{day}/#{month}/#{year}</span> <span class='comment__id'>##{comment.id}</span></div> <div class='comment__text'>#{comment.text}</div>"
thread.appendChild div
# If it's not a reply
if comment.reply is null
# Add to beginning
threads.prepend thread
else
# Add to thread
$id("thread-#{comment.reply}").appendChild thread
ids = $class 'comment__id'
for id in ids
do (id) ->
# Reply to comment when clicked on the id
id.addEventListener 'click', ->
reply = id.textContent.substring 1
replyTag.textContent = "Replying to #{id.textContent}"
replyTag.classList.remove 'comment-form__reply_hidden'
return
endLoading spinner
return
export default Comments