<?php

namespace Diamond\Modules\AdminBooks;

use ActiveTable\ColumnTable;
use Diamond\Application\GuestBook\GuestBookService;
use Core\ {
    Form\ControlBuilder,
    ModuleController
};
use Diamond\Domain\GuestBook\Contracts\GuestBookEntityInterface;
use Core\Helpers\Text;
use Diamond\Repositories\GuestBook\GuestBookCriteria;
use DiamondTable\TableFactory;


/**
 * Description of AdminBooks
 *
 * @author Diamond Code Generator
 */
class AdminBooks extends ModuleController
{

    public function __construct(private GuestBookService $guestBookService,
                                private TableFactory     $tableFactory,
                                private ControlBuilder   $controlBuilder)
    {
    }

    public function process(): string
    {

        $table = $this->tableFactory->buildAdminTable(
            $this->guestBookService->getBookRepository(), GuestBookCriteria::create(),
            'Новая книга'
        );

        $table
            ->setDefaultSortColumn('id','DESC')
            ->addColumn(
                (new ColumnTable('id', '№'))->setWidth(40)
            )
            ->addColumn(
                (new ColumnTable('title', 'Название'))
            )
            ->addColumn(
                (new ColumnTable('count', 'Кол-во сообщений'))
                    ->setFormat($this, 'formatCount')
            )
            ->addColumn(
                (new ColumnTable('desc', 'Описание'))
                    ->setFormat($this, 'formatDesc')
            )
            ->addColumn(
                (new ColumnTable('actions', ''))
                    ->setFormat($this, 'formatActions')
                    ->setWidth(120)
            );

        $table
            ->addField(
                $this
                    ->controlBuilder
                    ->buildInput('title'), true
            )
            ->addField(
                $this
                    ->controlBuilder
                    ->buildTextEditor('desc')
                    ->setHeight(200)
                    ->setCompact(true)
            );

        return $table->render();
    }

    public function formatActions(GuestBookEntityInterface $book): string
    {
        return $this->controlBuilder->buildActionMenuAdmin([
            anchor(
                admin_path('/diamond/content/book-items'),
                'Перейти к отзывам',
                [],
                [
                    'filter_by_bookId' => $book->getId()
                ]
            )
        ],
            $book->getId()
        )->render();
    }


    public function formatCount(GuestBookEntityInterface $book): string
    {
        return (string)$book->getItemsCount();
    }


    public function formatDesc(GuestBookEntityInterface $book): string
    {
        if (empty($book->getDesc())) {
            return '';
        }
        return Text::clearText($book->getDesc());
    }
}