<?php

namespace apexl\Io\modules\display\components;

use apexl\Io\modules\component\entities\componentEntity;
use apexl\Io\modules\display\includes\Page;
use apexl\Io\modules\menu\entities\menuEntity;
use apexl\Io\modules\menu\services\Menu;
use apexl\Io\services\pathUtility;

class TitleTile extends componentEntity
{
    protected $path;
    protected $menu;

    protected $title;

    public function __construct(Page $page = null)
    {
        parent::__construct();
        $this->path = pathUtility::getInstance();
        $this->menu = Menu::getInstance();

        $this->setColWidth('sm', 12);
        $this->headerSize(1);

        //set a reference so we can track page title changes.
        if ($page !== null) {
            $this->text($page->pageTitle);
        }
    }

    /**
     * @param $size
     * @return $this
     */
    public function headerSize($size)
    {
        $this->addProperty('header', $size);

        return $this;
    }

    /**
     * @param $text
     * @return $this
     */
    public function text($text)
    {
        $this->addProperty('title', ucfirst(($text) ?? ""));

        return $this;
    }

    /**
     * Hook Page__setPageTitle
     * @param $text
     * @return mixed
     */
    public function titleCallback($text)
    {
        $this->text($text);

        return $text;
    }

    /**
     * @return TitleTile
     */
    public function addBreadcrumbs(menuEntity $menu)
    {
        $this->addProperty('breadcrumbs', $menu->generateBreadcrumbs($this->path->getPath()));

        return $this;
    }

    public function __toString(): string
    {
        //we're outputting so check the final title values
        $titleRoute = $this->menu->getMenuItem($this->path->getPath());
        $this->text($this->title ?? $titleRoute->title ?? '');

        return parent::__toString();
    }
}
