<?php

namespace App\Livewire;

use App\Models\Episode;
use App\Models\User;
use Livewire\Component;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;

use Maize\Markable\Models\Like;

class LikeButton extends Component
{
    public $episodeId = 0;

    public $likeCount = 0;

    public $liked = false;

    public function mount(Episode $episode)
    {
        $this->episodeId = $episode->id;
        $this->likeCount = $episode->likes->count();

        if (Auth::check()) {
            $this->liked = Like::has($episode, User::where('id', Auth::user()->id)->firstOrFail());
        }
    }

    public function update()
    {
        $episode = Episode::where('id', $this->episodeId)->firstOrFail();
        $this->likeCount = $episode->likes->count();

        if (Auth::check()) {
            $this->liked = Like::has($episode, User::where('id', Auth::user()->id)->firstOrFail());
        }
    }

    public function like()
    {
        if (! Auth::check()) {
            return;
        }

        $episode = Episode::where('id', $this->episodeId)->firstOrFail();
        Like::toggle($episode, User::where('id', Auth::user()->id)->firstOrFail());

        Cache::forget('episodeLikes'.$this->episodeId);

        if ($this->liked) {
            $this->liked = false;
            $this->likeCount--;
            return;
        }

        $this->liked = true;
        $this->likeCount++;
    }

    public function render()
    {
        return view('livewire.like-button');
    }
}
