<?php

namespace Ignite\Core\Models\Import;

use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\Collection;

class LogPaginator
{
    /**
     * @var Request
     */
    protected $request;

    /**
     * ImportLogPaginator constructor.
     *
     * @param Request $request
     */
    public function __construct(Request $request)
    {
        $this->request = $request;
    }

    /**
     * Paginate the given collection of log files.
     *
     * @param  Collection $items
     * @param  int $perPage
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function paginate(Collection $items, $perPage = 25)
    {
        if ($this->request->has('onlyErrors')) {
            $items = $items->filter([$this, 'filterForErrors']);
        } elseif ($this->request->has('onlyImported')) {
            $items = $items->filter([$this, 'filterForImported']);
        }

        $page = Paginator::resolveCurrentPage();
        $path = Paginator::resolveCurrentPath();

        return new LengthAwarePaginator(
            $items->forPage($page, $perPage),
            $items->count(),
            $perPage,
            $page,
            ['path' => $path]
        );
    }

    /**
     * Filter the collection to show only errors.
     *
     * @param  array $line
     * @return bool
     */
    public function filterForErrors(array $line)
    {
        return 'error' === strtolower($line['type']);
    }

    /**
     * Filter the collection to show only errors.
     *
     * @param  array $line
     * @return bool
     */
    public function filterForImported(array $line)
    {
        return 'success' === strtolower($line['type']);
    }
}
