<?php

namespace Ignite\Core\Repositories;

use Ignite\Core\Entities\Block;
use Ignite\Core\Contracts\Repositories\BlockRepository as BlockRepositoryInterface;
use Illuminate\Database\Eloquent\Builder;

class BlockRepository implements BlockRepositoryInterface
{
    /**
     * The default raw query builder object.
     *
     * @return Builder
     */
    public function findRaw()
    {
        return Block::query();
    }

    /**
     * Find all blocks.
     *
     * @param  int $limit
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator|\Illuminate\Database\Eloquent\Collection
     */
    public function findAll($limit = null)
    {
        if (is_null($limit)) {
            return $this->findRaw()->get();
        }

        return $this->findRaw()->paginate($limit);
    }

    /**
     * Find one block by primary key.
     *
     * @param  int $id
     * @return Block
     */
    public function find($id)
    {
        return Block::findOrFail($id);
    }

    /**
     * Find one block by primary key.
     *
     * @param  int $code
     * @return Block
     */
    public function findByCode($code)
    {
        try {
            $block = $this->findRaw()
                ->byCode($code)
                ->onlyActive()
                ->onlyPublished()
                ->firstOrFail();
        } catch (\Exception $e) {
            $block = new Block();
        }

        return $block;
    }

    /**
     * Create a new block.
     *
     * @param  array $data
     * @return Block
     */
    public function create(array $data)
    {
        return Block::create($data);
    }

    /**
     * Update a block using the id to locate it.
     *
     * @param  int $id
     * @param  array $data
     * @return Block
     */
    public function update($id, array $data)
    {
        $block = $this->find($id);

        $block->fill($data)->save();

        return $block;
    }

    /**
     * Delete many blocks via multiple block IDs.
     *
     * @param  int $id
     * @return bool
     * @throws \Exception
     */
    public function delete($id)
    {
        return $this->find($id)->delete();
    }

    /**
     * Delete many blocks via multiple block IDs.
     *
     * @param  array $ids
     * @return int
     */
    public function deleteMany(array $ids)
    {
        return Block::destroy($ids);
    }
}
