<?php

namespace idoit\Module\Forms\Model\CategoryTypes;

use idoit\Module\Forms\Model\CategoryTypes\Virtual\VirtualCategory;
use idoit\Module\Multiedit\Model\Categories;
use isys_application;
use isys_cmdb_dao_category;
use ReflectionClass;

class VirtualCategories extends Categories
{
    public function setData()
    {
        $virtualDirectory = __DIR__ . '/Virtual/';
        $handle = opendir($virtualDirectory);
        $rootNamespace = 'idoit\\Module\\Forms\\Model\\CategoryTypes\\Virtual';
        $container = isys_application::instance()->container;

        while (false !== ($file = readdir($handle))) {

            if ($file === '.' || $file === '..' || !is_dir($virtualDirectory . $file)) {
                continue;
            }

            $categoryFilter = $this->getFilter()->getCategories();
            $categoryHandler = opendir($virtualDirectory . $file);
            $categoryNamespace = $rootNamespace . '\\' . $file;

            while (false !== ($categoryFile = readdir($categoryHandler))) {
                if ($categoryFile === '.' || $categoryFile === '..') {
                    continue;
                }

                $class = $categoryNamespace . '\\' . substr($categoryFile, 0, strpos($categoryFile, '.'));

                if (!class_exists($class)) {
                    include_once $virtualDirectory . $file . '/' . $categoryFile;
                }

                $reflection = new ReflectionClass($class);

                if (!$reflection->implementsInterface(VirtualCategory::class) ||
                    !$reflection->isSubclassOf(isys_cmdb_dao_category::class)) {
                    continue;
                }

                /**
                 * @var isys_cmdb_dao_category $daoInstance
                 */
                $daoInstance = $class::instance($container->get('database'));

                if (count($categoryFilter) && !in_array($daoInstance->getVirtualCategoryConst(), $categoryFilter, true)) {
                    continue;
                }

                $this->data[$daoInstance->getVirtualCategoryConst() . ':' . $class] = $container->get('language')
                    ->get($daoInstance->getCategoryTitle());

                if ($daoInstance->is_multivalued()) {
                    $this->addToMultivalueCategories($daoInstance->get_category_const());
                }
            }
        }

        return $this;
    }
}
