import Cookies from 'js-cookie'

let cookieValues = JSON.parse(Cookies.get('likes') || '{}')

function checkLikeList() {
	const $likeList = $('.like-button--list')

	if ($likeList) {
		// Listagem de posts
		$likeList.each(function() {
			let id = $(this).attr('data-post-id')

			if (cookieValues[id]) {
				$(this).addClass('is-active')
				$(this)
					.find('i')
					.removeClass('icon-dislike')
				$(this)
					.find('i')
					.addClass('icon-like')
			}
		})
	}
}

$(function() {
	const $likeArticle = $('.like-button--article')

	checkLikeList()

	if ($likeArticle) {
		// Interna de post
		let id = $likeArticle.attr('data-post-id')

		if (cookieValues[id]) {
			$likeArticle.addClass('is-active')
			$likeArticle.find('i').removeClass('icon-dislike')
			$likeArticle.find('i').addClass('icon-like')
		}
	}

	$('body').on('click', '.like-button', function(e) {
		const $this = $(this)
		e.preventDefault()

		let likesCount = $this.find('span').text()
		let id = $this.attr('data-post-id')

		cookieValues = JSON.parse(Cookies.get('likes') || '{}')

		if (cookieValues[id]) {
			console.log('already like')
			return
		}

		likesCount++
		$this.find('span').text(likesCount)
		$this.addClass('is-active')

		$this
			.find('i')
			.removeClass('icon-dislike')
			.addClass('icon-like')
		// console.log(`${SERVER_URL}/send_like/${id}`)
		$.ajax({
			type: 'GET',
			// url: `${SERVER_URL}/send_like/${id}`,
			success: function(data) {
				cookieValues[id] = 1
				Cookies.set('likes', JSON.stringify(cookieValues))
			},
			error: function(data) {
				console.log('Erro')

				likesCount--
				$this.find('span').text(likesCount)
				$this
					.find('i')
					.addClass('icon-dislike')
					.removeClass('icon-like')
				$this.removeClass('is-active')
			}
		})
	})
})

window.checkLikeList = checkLikeList
