<?php

namespace idoit\Module\Cmdb\Component\CategoryChanges\Type\Browser;

use idoit\Component\Property\Property;
use idoit\Module\Cmdb\Component\CategoryChanges\Data\ChangesData;
use idoit\Module\Cmdb\Component\CategoryChanges\Data\DefaultData;
use idoit\Module\Cmdb\Component\CategoryChanges\Data\RequestData;
use idoit\Module\Cmdb\Component\CategoryChanges\Data\SmartyData;
use idoit\Module\Cmdb\Component\CategoryChanges\Type\TypeInterface;
use isys_application;
use isys_cmdb_dao_category;
use isys_format_json;
use isys_popup_browser_object_ng;
use isys_tenantsettings;

class MultiSecondSelectObjectBrowserType extends AbstractBrowserType implements TypeInterface, ObjectBrowserTypeInterface
{
    /**
     * @param Property $property
     * @param string   $tag
     *
     * @return bool
     */
    public function isApplicable(Property $property, string $tag)
    {
        $params = $property->getUi()->getParams();
        return $property->getInfo()->getType() === Property::C__PROPERTY__INFO__TYPE__OBJECT_BROWSER &&
            $params[isys_popup_browser_object_ng::C__MULTISELECTION] &&
            $params[isys_popup_browser_object_ng::C__SECOND_SELECTION] &&
            $params['p_strPopupType'] === 'browser_object_ng';
    }

    /**
     * @param string                 $tag
     * @param isys_cmdb_dao_category $dao
     * @param RequestData            $requestDataProvider
     * @param SmartyData             $smartyDataProvider
     * @param array                  $currentData
     *
     * @return array|null
     */
    public function handlePostData(string $tag, isys_cmdb_dao_category $dao, RequestData $requestDataProvider, SmartyData $smartyDataProvider, array $currentData = [])
    {
        $requestData = $requestDataProvider->getData();
        $smartyData = $smartyDataProvider->getData();
        $property = $this->getProperty();
        $uiField = $property->getUi()
            ->getId();
        $alwaysInLogbook = $property->getInfo()->isAlwaysInLogbook();
        $uiHiddenField = $uiField . '__HIDDEN';
        $uiConfigField = $uiField . '__CONFIG';
        $currentObjectId = $dao->get_object_id();
        $currentPropertyTag = $this->getCurrentPropertyTag($dao, $tag);
        $changes = [];

        $oldValueConfig = is_string($requestData[$uiConfigField]) ? isys_format_json::decode($requestData[$uiConfigField]) : [];
        $oldValueId = str_replace('"', '', (string)$oldValueConfig['p_strSelectedID']);
        $oldValue = $oldValueConfig['p_strValue'] ? explode(', ', trim((string)$oldValueConfig['p_strValue'])) : [];
        $newValueId = (string)$requestData[$uiHiddenField];
        $newValue = isys_tenantsettings::get('gui.empty_value', '-');
        $formatSelectionListFormat = $oldValueConfig[isys_popup_browser_object_ng::C__SECOND_LIST_FORMAT];
        [$selectionClass, $selectionMethod] = explode('::', $formatSelectionListFormat);

        if (isys_format_json::is_json_array($newValueId)) {
            $newValueId = isys_format_json::decode($newValueId);
            asort($newValueId);
        }

        if (isys_format_json::is_json_array($oldValueId)) {
            $oldValueId = isys_format_json::decode($oldValueId);
            asort($oldValueId);
        }

        $valueCheck = empty(array_diff($oldValueId, $newValueId)) && empty(array_diff($newValueId, $oldValueId));
        $selectionClassCheck = class_exists($selectionClass);

        if (!$selectionClassCheck || ($valueCheck && !$alwaysInLogbook)) {
            return [];
        }

        $selectionClassInstance = $selectionClass::instance(isys_application::instance()->container->get('database'));
        if (!method_exists($selectionClassInstance, $selectionMethod)) {
            return [];
        }

        if (is_array($newValueId) && !empty($newValueId)) {
            $newValueIds = isys_format_json::decode($newValueId);
            $newValueArr = [];
            foreach ($newValueIds as $id) {
                $newValueArr[] = (string)$selectionClassInstance->$selectionMethod($id, true);
            }
            $newValue = $newValueArr;
        }
        asort($oldValue);
        asort($newValue);

        $oldValue = implode(', ', $oldValue);
        $newValue = implode(', ', $newValue);

        $changes = ChangesData::factory(
            [
                $currentPropertyTag => [
                    self::CHANGES_FROM => $oldValue,
                    self::CHANGES_TO => $newValue
                ]
            ],
            $currentObjectId
        );

        return [
            self::CHANGES_CURRENT => $changes,
            self::CHANGES_TO => $changes,
        ];
    }

    public function handleRanking()
    {
        // TODO: Implement handleRanking() method.
    }

    public function handleData(DefaultData $currentData, DefaultData $changedData)
    {
        // TODO: Implement handleData() method.
    }
}
