<?php

declare(strict_types=1);

namespace FiloBlu\Refilo\Helper\ContentManager;

use Blackbird\ContentManager\Api\Data\ContentTypeInterface;
use Blackbird\ContentManager\Api\Data\ContentTypeInterfaceFactory;
use Blackbird\ContentManager\Model\ResourceModel\ContentType\CollectionFactory;
use Magento\Framework\DataObject;

/**
 *
 */
class Data
{
    /**
     * @var CollectionFactory
     */
    protected $contentTypeCollectionFactory;

    private $contentTypes;
    /**
     * @var ContentTypeInterfaceFactory
     */
    private $contentTypeInterfaceFactory;
    /**
     * @var
     */
    private $default;

    /**
     * @param \Blackbird\ContentManager\Model\ResourceModel\ContentType\CollectionFactory $contentTypeCollectionFactory
     * @param \Blackbird\ContentManager\Api\Data\ContentTypeInterfaceFactory $contentTypeInterfaceFactory
     */
    public function __construct(
        CollectionFactory $contentTypeCollectionFactory,
        ContentTypeInterfaceFactory $contentTypeInterfaceFactory
    ) {
        $this->contentTypeCollectionFactory = $contentTypeCollectionFactory;
        $this->contentTypeInterfaceFactory = $contentTypeInterfaceFactory;
    }

    /**
     * @param $ctId
     * @return mixed|null
     */
    public function get($ctId): ContentTypeInterface
    {
        if (!$this->contentTypes) {
            $this->contentTypes = [];
            $types = $this->contentTypeCollectionFactory->create()->getItems();
            foreach ($types as $type) {
                $this->contentTypes[$type->getId()] = $type;
            }
            $this->default = $this->contentTypeInterfaceFactory->create();
        }
        return $this->contentTypes[$ctId] ?? $this->default;
    }

    /**
     * @param $ctId
     * @return string
     */
    public function getIdentifierFromId($ctId)
    {
        return  $this->get($ctId)->getIdentifier();
    }

    /**
     * @param $ctId
     * @return mixed
     */
    public function getDataFromId($ctId)
    {
        return $this->get($ctId)->getData();
    }

    /**
     * @return DataObject[]
     */
    public function getContentTypeList()
    {
        return $this->contentTypeCollectionFactory->create()->getItems();
    }
}
