<?php

use idoit\Component\FeatureManager\FeatureCheckInterface;
use idoit\Component\FeatureManager\FeatureManager;
use idoit\Component\Property\Exception\UnsupportedConfigurationTypeException;
use idoit\Component\Property\Type\CommentaryProperty;
use idoit\Component\Property\Type\DialogProperty;
use idoit\Component\Property\Type\TextAreaProperty;
use idoit\Component\Property\Type\TextProperty;
use idoit\Module\Cmdb\Interfaces\Legacy\ComparableCategory;

/**
 * i-doit
 *
 * DAO: global category for JDisc custom attributes.
 *
 * @package     i-doit
 * @subpackage  CMDB_Categories
 * @copyright   i-doit GmbH
 * @license     http://www.i-doit.com/license
 */
class isys_cmdb_dao_category_g_jdisc_ca extends isys_cmdb_dao_category_global implements ComparableCategory, FeatureCheckInterface
{
    public function __construct(isys_component_database $p_db)
    {
        $this->m_category = 'jdisc_ca';
        $this->m_multivalued = true;

        parent::__construct($p_db);

        $this->categoryTitle = 'LC__CMDB__CATG__JDISC_CUSTOM_ATTRIBUTES';
        $this->m_is_purgable = true;
    }

    /**
     * Wrapper for create data
     *
     * @param array $p_data
     * @return int|bool
     * @throws isys_exception_dao
     * @throws isys_exception_dao_cmdb
     * @throws isys_exception_database
     */
    public function create_data($p_data)
    {
        $l_attributes = $this->get_attribute_types();

        if (isset($_POST['C__CATG__JDISC__CUSTOM_ATTRIBUTES__TYPE'])) {
            switch ($l_attributes[$p_data['attribute_type']]['isys_jdisc_ca_type__const']) {
                case 'C__JDISC__CA_TYPE__CURRENCY':
                    $p_data['attribute_content'] = ((float)$p_data['attribute_content'] * 100);
                    break;

                case 'C__JDISC__CA_TYPE__DATE':
                    $p_data['attribute_content'] = date('Y-m-d', strtotime($p_data['attribute_content']));
                    break;
            }
        }

        return parent::create_data($p_data);
    }

    /**
     * @param      $categoryDataValues
     * @param      $currentCategoryDataValues
     * @param      $usedProperties
     * @param      $comparison
     * @param      $badness
     * @param      $mode
     * @param      $categoryId
     * @param      $unitKey
     * @param      $categoryDataIds
     * @param      $localExport
     * @param      $datasetIdChanged
     * @param      $datasetId
     * @param      $logger
     * @param null $categoryName
     * @param null $table
     * @param null $multivalued
     * @param null $categoryTypeId
     * @param null $categoryIds
     * @param null $objectIds
     * @param null $alreadyUsedDataIds
     */
    public function compare_category_data(
        &$categoryDataValues,
        &$currentCategoryDataValues,
        &$usedProperties,
        &$comparison,
        &$badness,
        &$mode,
        &$categoryId,
        &$unitKey,
        &$categoryDataIds,
        &$localExport,
        &$datasetIdChanged,
        &$datasetId,
        &$logger,
        &$categoryName = null,
        &$table = null,
        &$multivalued = null,
        &$categoryTypeId = null,
        &$categoryIds = null,
        &$objectIds = null,
        &$alreadyUsedDataIds = null
    ) {
        $check = function ($importetTitle, $importedType, $importedContent, $currentTitle, $currentType, $currentContent) {
            return $importetTitle === $currentTitle
                && $importedType === $currentType
                && $importedContent === $currentContent;
        };

        $importedTitle = $categoryDataValues['properties']['title'][C__DATA__VALUE];
        $importedContent = str_replace(["\r", "\n", "\t", " "], "", $categoryDataValues['properties']['attribute_content'][C__DATA__VALUE]);
        $importedType = (int)$categoryDataValues['properties']['attribute_type']['id'];

        // Iterate through local data sets:
        foreach ($currentCategoryDataValues as $dataSetKey => $dataset) {
            $datasetIdChanged = false;
            $datasetId = $dataset[$table . '__id'];
            $currentContent = str_replace(["\r", "\n", "\t", " "], "", $dataset[$table . '__attribute_content']);
            $currentTitle = $dataset[$table . '__title'];
            $currentType = (int)$dataset[$table . '__isys_jdisc_ca_type__id'];

            if (isset($alreadyUsedDataIds[$datasetId])) {
                // Skip it ID has already been used
                $p_comparison[isys_import_handler_cmdb::C__COMPARISON__DIFFERENT][$dataSetKey] = $datasetId;
                $logger->debug('  Dateset ID "' . $datasetId . '" has already been handled. Skipping to next entry.');
                continue;
            }

            if ($mode === isys_import_handler_cmdb::C__USE_IDS && $categoryDataValues['data_id'] !== $datasetId) {
                $badness[$datasetId]++;
                $datasetIdChanged = true;

                if ($mode === isys_import_handler_cmdb::C__USE_IDS) {
                    continue;
                }
            }

            if ($check($importedTitle, $importedType, $importedContent, $currentTitle, $currentType, $currentContent) === true) {
                $comparison[isys_import_handler_cmdb::C__COMPARISON__SAME][$dataSetKey] = $datasetId;

                return;
            } else {
                $comparison[isys_import_handler_cmdb::C__COMPARISON__DIFFERENT][$dataSetKey] = $datasetId;
            }
        }
    }

    /**
     * Method for returning the properties.
     *
     * @return  array
     * @throws UnsupportedConfigurationTypeException
     */
    protected function properties()
    {
        return [
            'attribute'         => new TextProperty(
                'C__CATG__JDISC__CUSTOM_ATTRIBUTES__TITLE',
                'LC__CATG__JDISC__CUSTOM_ATTRIBUTES__ATTRIBUTE',
                'isys_catg_jdisc_ca_list__title',
                'isys_catg_jdisc_ca_list',
            ),
            'attribute_content'         => new TextProperty(
                'C__CATG__JDISC__CUSTOM_ATTRIBUTES__CONTENT',
                'LC__CATG__JDISC__CUSTOM_ATTRIBUTES__CONTENT',
                'isys_catg_jdisc_ca_list__content',
                'isys_catg_jdisc_ca_list',
            ),
            'attribute_type'         => new DialogProperty(
                'C__CATG__JDISC__CUSTOM_ATTRIBUTES__TYPE',
                'LC__CATG__JDISC__CUSTOM_ATTRIBUTES__TYPE',
                'isys_catg_jdisc_ca_list__isys_jdisc_ca_type__id',
                'isys_catg_jdisc_ca_list',
                'isys_jdisc_ca_type'
            ),
            'attribute_folder'  => new TextAreaProperty(
                'C__CATG__JDISC__CUSTOM_ATTRIBUTES__FOLDER',
                'LC__CATG__JDISC__CUSTOM_ATTRIBUTES__FOLDER',
                'isys_catg_jdisc_ca_list__folder',
                'isys_catg_jdisc_ca_list',
            ),
            'description'       => new CommentaryProperty(
                'C__CMDB__CAT__COMMENTARY_' . C__CMDB__CATEGORY__TYPE_GLOBAL . defined_or_default('C__CATG__JDISC_CA', 'C__CATG__JDISC_CA'),
                'isys_catg_jdisc_ca_list__description',
                'isys_catg_jdisc_ca_list',
            )
        ];
    }

    /**
     * Wrapper for save_data
     *
     * @param int   $p_category_id
     * @param array $p_data
     * @return bool
     * @throws isys_exception_dao
     * @throws isys_exception_dao_cmdb
     * @throws isys_exception_database
     */
    public function save_data($p_category_id, $p_data)
    {
        $l_attributes = $this->get_attribute_types();

        if (isset($_POST['C__CATG__JDISC__CUSTOM_ATTRIBUTES__TYPE'])) {
            switch ($l_attributes[$p_data['attribute_type']]['isys_jdisc_ca_type__const']) {
                case 'C__JDISC__CA_TYPE__CURRENCY':
                    $p_data['attribute_content'] = ((float)$p_data['attribute_content'] * 100);
                    break;

                case 'C__JDISC__CA_TYPE__DATE':
                    $p_data['attribute_content'] = date('Y-m-d', strtotime($p_data['attribute_content']));
                    break;
            }
        }

        return parent::save_data($p_category_id, $p_data);
    }

    /**
     * Retrieves all custom attribute types
     *
     * @return array
     * @throws isys_exception_database
     */
    public function get_attribute_types(): array
    {
        $return = [];
        $result = $this->retrieve('SELECT * FROM isys_jdisc_ca_type;');

        while ($row = $result->get_row()) {
            $return[$row['isys_jdisc_ca_type__id']] = $row;
        }

        return $return;
    }

    /**
     * @return bool
     */
    public static function isFeatureEnabled(): bool
    {
        return FeatureManager::isFeatureActive('jdisc-category');
    }
}
