<?php

namespace Velis\Mvc\Controller\Decorator;

use Exception;

class ItemListDecorator
{
    private $list;
    private $decoratorClass;
    private $decoratedList = [];
    private $di;

    /**
     * ItemList constructor.
     *
     * @param $list
     * @param $decoratorClass
     * @param array $di
     */
    public function __construct(array $list, string $decoratorClass, $di = [])
    {
        $this->list           = $list;
        $this->decoratorClass = $decoratorClass;
        $this->di             = $di;
    }

    public function setList(array $list): void
    {
        $this->list = $list;
    }

    /**
     * getList
     */
    private function getList(string $context)
    {
        $decoratorClass = $this->decoratorClass;

        foreach ($this->list as $item) {
            /** @var AbstractItemDecorator $decorator */
            $decorator = new $decoratorClass($item, $this->di);

            if (!($decorator instanceof AbstractItemDecorator)) {
                throw new Exception('Decorator class is not an instance of AbstractItemDecorator');
            }
            $this->decoratedList[] = $decorator->getData($context);
        }

        return $this->decoratedList;
    }

    public function getData(string $context = AbstractItemDecorator::LIST_CONTEXT)
    {
        switch ($context) {
            case AbstractItemDecorator::SELECT_CONTEXT:
            case AbstractItemDecorator::LIST_CONTEXT:
                return $this->getList($context);
                break;
            default:
                return [];
                break;
        }
    }
}
