<?php

namespace App\Packages\v4\Capsule\Repository;

use App\Packages\Capsule\Models\Capsule;
use App\Packages\Capsule\Models\CapsuleComment;
use App\Packages\User\Models\User;
use App\Packages\v4\Core\Repository\AbstractRepository;
use Illuminate\Support\Collection;

/**
 * Class CapsuleCommentRepository
 * @package App\Packages\Capsule\Repository
 *
 * @method CapsuleComment firstById($id)
 *
 * @property CapsuleComment $model
 */
class CapsuleCommentRepository extends AbstractRepository
{
	const LIMIT_COMMENT = 5;

	public static function init()
    {
        return new CapsuleCommentRepository(CapsuleComment::class);
    }

	/**
	 * @param $uuid
	 *
	 * @return CapsuleComment|null|object
	 */
	public function firstByUuid($uuid)
	{
		return $this->query()->where('uuid', '=', $uuid)->first();
	}

	/**
	 * @param Capsule $capsule
	 *
	 * @return Collection|User[]
	 */
	public function lastUsersCommented(Capsule $capsule)
	{
		return User::query()
			->leftJoin('table_capsule_comment', 'table_capsule_comment.user_id', '=', 'table_user.id')
			->where('table_capsule_comment.capsule_id', '=', $capsule->id)
			->orderBy('table_capsule_comment.created_at', 'desc')
			->take(static::LIMIT_COMMENT)
			->get();
	}

    /**
     * @param Capsule $capsule
     *
     * @return Collection|CapsuleComment[]
     */
    public function lastCapsuleComments(Capsule $capsule)
    {
        return $this->query()
            ->with(['user'])
            ->where('table_capsule_comment.capsule_id', '=', $capsule->id)
            ->orderBy('table_capsule_comment.created_at', 'desc')
            ->take(static::LIMIT_COMMENT)
            ->get();
    }

	/**
	 * @param Capsule $capsule
	 *
	 * @return Collection|CapsuleComment[]
	 */
	public function capsuleComments(Capsule $capsule)
	{
		return $this->query()
			->with(['user'])
			->where('table_capsule_comment.capsule_id', '=', $capsule->id)
			->orderBy('table_capsule_comment.created_at', 'desc')
			->get();
	}

    /**
     * @param Capsule $capsule
     *
     * @return int
     */
    public function capsuleCommentsCount(Capsule $capsule)
    {
        return $this->query()
            ->where('table_capsule_comment.capsule_id', '=', $capsule->id)
            ->count();
    }
}
