<?php

namespace App\Http\Traits;

use Illuminate\Pagination\Paginator;
use Illuminate\Pagination\LengthAwarePaginator;
use stdClass;

trait PagingTrait
{
    public function getPageOffset(int $page = 1, int $perPage = DEFAULT_LIST_PER_PAGE): int
    {
        return ($page > 0 ? (($page - 1) * $perPage) : 1);
    }

    public function getPaginator(array $items, int $total, int $perPage, int|null $page, string $path = null, string $query = null): LengthAwarePaginator
    {
        $request = Request();

        return new LengthAwarePaginator($items, $total, $perPage, $page, [
            'path' => ($path ?? $request->url()),
            'query' => ($query ?? $request->query())
        ]);
    }

    /**
     * generate a hierarchical structure of comments for loop
     * @param object $list
     * @param int $total
     */
    public function generateList(object $list, int $total = 0)
    {
        $root = new stdClass;
        for ($i = $total - 1; $i >= 0; $i--) {
            $key = $list[$i]->key;
            $parent = $list[$i]->parent;
            if (!$key) {
                continue;
            }
            $list[$key] = $list[$i];
            if ($parent) {
                $list[$parent]->child[] = &$list[$key];
            } else {
                $root->child[] = &$list[$key];
            }
        }
        $this->relocateList($list, $root->child, 0, null);
    }

    /**
     * Relocate comments in the hierarchical structure
     * @param $pList
     * @param array $cList
     * @param $depth
     * @param null $parent
     */
    private function relocateList(&$pList, array $cList, $depth, $parent = null)
    {
        if (!is_array($cList) || !count($cList)) {
            return;
        }

        foreach ($cList as $key => $val) {
            if ($parent) {
                $val->head = $parent->head;
            } else {
                $val->head = $val->comment_srl;
            }

            $val->arrange = count($pList) + 1;

            if ($val->child) {
                $val->depth = $depth;
                $pList[$val->comment_srl] = $val;
                $this->relocateList($pList, $val->child, $depth + 1, $val);
                unset($val->child);
            } else {
                $val->depth = $depth;
                $pList[$val->comment_srl] = $val;
            }
        }
    }
}
