<?php

namespace idoit\Module\Forms\Model\Processors;

use idoit\Module\Forms\Exceptions\DataByAttributeException;
use idoit\Module\Forms\Exceptions\ProcessorException;
use idoit\Module\Forms\Model\AttributeDao;
use isys_application;
use isys_cmdb_dao_category;

abstract class AbstractProcessor
{
    /**
     * @var string
     */
    protected static $categoryConst = '';

    /**
     * @var string[]
     */
    protected static $categoryDependency = [];

    /**
     * @var isys_cmdb_dao_category
     */
    protected $dao;

    /**
     * @var array
     */
    protected $dependentSyncData = [];

    /**
     * @param isys_cmdb_dao_category $dao
     */
    public function __construct(isys_cmdb_dao_category $dao) {
        $this->dao = $dao;
    }

    /**
     * @return static
     * @throws DataByAttributeException
     * @throws ProcessorException
     * @throws \isys_exception_database
     */
    public static function factory()
    {
        $db = isys_application::instance()->container->get('database');
        $attributeDao = AttributeDao::instance($db);
        $categoryConst = static::$categoryConst;

        $result = $attributeDao->getByCategory([$categoryConst]);

        if (count($result)) {
            $className = $result[0]['className'];

            if (!class_exists($className)) {
                throw DataByAttributeException::CategoryDaoDoesNotExist($categoryConst);
            }

            return new static(new $className($db));
        }

        throw ProcessorException::ProcessorCouldNotBeLoaded($categoryConst);
    }

    /**
     * @return mixed
     */
    public function getDao()
    {
        return $this->dao;
    }

    /**
     * @return string
     */
    public static function getCategoryConst()
    {
        return static::$categoryConst;
    }

    /**
     * @param array $syncData
     */
    public function setDependentSyncData(array $syncData)
    {
        if (empty(static::$categoryDependency)) {
            return;
        }

        foreach (static::$categoryDependency as $categoryConst) {
            $this->dependentSyncData[$categoryConst] = $syncData[$categoryConst];
        }
    }
}
