<?php

namespace Lightscale\LaralightTables;

use Lightscale\LaralightTables\Toolbar\Item as ToolbarItem;
use Lightscale\LaralightTables\Toolbar\Search as SearchItem;
use Lightscale\LaralightTables\Toolbar\PageSize as PageSizeItem;
use Lightscale\LaralightTables\Toolbar\Filter as FilterItem;

use Illuminate\View\View;
use Illuminate\Support\Collection;

class Toolbar
{
    protected ?SearchItem $searchItem = null;
    protected ?PageSizeItem $pageSizeItem = null;

    protected Collection $startItems;
    protected Collection $midItems;
    protected Collection $endItems;
    protected Collection $filterItems;

    public function __construct(
        private TableComponent $table
    )
    {
        $this->startItems = collect();
        $this->midItems = collect();
        $this->endItems = collect();
        $this->filterItems = collect();
    }

    private function addItem(Collection $list, ToolbarItem $item): static
    {
        $item->setToolbar($this);

        if ($item instanceof FilterItem) {
            $this->filterItems->push($item);
        }
        else if ($item instanceof PageSizeItem) {
            $this->pageSizeItem = $item;
        }
        else if ($item instanceof SearchItem) {
            $this->searchItem = $item;
        }

        $list->push($item);
        return $this;
    }

    public function addStartItem(ToolbarItem $item): static
    {
        return $this->addItem($this->startItems, $item);
    }

    public function addMidItem(ToolbarItem $item): static
    {
        return $this->addItem($this->midItems, $item);
    }

    public function addEndItem(ToolbarItem $item): static
    {
        return $this->addItem($this->endItems, $item);
    }

    public function getTable(): TableComponent
    {
        return $this->table;
    }

    public function getSearch(): ?SearchItem
    {
        return $this->searchItem;
    }

    public function getPageSize(): ?PageSizeItem
    {
        return $this->pageSizeItem;
    }

    public function getFilters(): Collection
    {
        return $this->filterItems;
    }

    public function render(): View
    {
        return view('laralight-tables::toolbar', [
            'startItems' => $this->startItems,
            'midItems' => $this->midItems,
            'endItems' => $this->endItems,
        ]);
    }

}