<?php declare(strict_types = 1);

namespace idoit\Module\SyneticsFlows\ConnectSignal;

use idoit\Module\SyneticsFlows\Automation\Trigger\Invocation\ButtonInvocation;
use idoit\Module\SyneticsFlows\Automation\Trigger\Invocation\ObjectCategoryContext;
use idoit\Module\SyneticsFlows\Automation\Trigger\Invocation\ObjectContext;
use idoit\Module\SyneticsFlows\Automation\Trigger\TriggerType\ButtonTriggerType;
use idoit\Module\SyneticsFlows\Automation\TriggerService;
use isys_cmdb_dao;
use isys_component_template;
use isys_module_synetics_flows;

class AddButtonConnect
{
    public function __construct(
        private isys_component_template $templates,
        private TriggerService $service,
        private isys_cmdb_dao $cmdbDao
    )
    {
    }

    public function __invoke(string $type, array $pageData): void
    {
        $objectId = $pageData['isys_obj__id'] ?? null;
        $objectType = $pageData['isys_obj_type__id'] ?? null;
        $objectStatus = $pageData['isys_obj__status'] ?? null;

        if (!is_string($objectId) || (int) $objectStatus <= C__RECORD_STATUS__BIRTH) {
            return;
        }

        $catConst = $this->getCategoryConstParam();
        $context = $catConst
            ? new ObjectCategoryContext($objectId, $objectType, $catConst)
            : new ObjectContext($objectId, $objectType);

        $flows = $this->service->findAutomations(new ButtonInvocation(null, $context, null));
        $buttons = [];

        foreach ($flows as $flow) {
            if ($flow->getTrigger() instanceof ButtonTriggerType) {
                $buttons[] = [
                    'trigger' => [
                        'name' => $flow->getTrigger()->getName(),
                        'icon' => $flow->getTrigger()->getIcon(),
                        'group' => $flow->getTrigger()->getGroup(),
                    ],
                    'automation' => [
                        'id' => $flow->getId(),
                        'name' => $flow->getName(),
                    ]
                ];
            }
        }

        global $index_includes;
        $index_includes['contenttopobjectdetail'][] = isys_module_synetics_flows::getPath() . 'templates/button.tpl';
        $this->templates->assign('triggerButtons', $buttons);
    }

    /**
     * @return string|null
     */
    private function getCategoryConstParam(): ?string
    {
        $catConst = 'C__CATG__GLOBAL';

        $types = [
            C__CMDB__GET__CATS => 's',
            C__CMDB__GET__CATG => 'g',
            C__CMDB__GET__CATG_CUSTOM => 'g_custom',
        ];

        foreach ($types as $key => $type) {
            if ($catId = isys_glob_get_param($key)) {
                $catConst = $this->cmdbDao->get_cat_const_by_id($catId, $type);
                break;
            }
        }

        return $catConst ? (string) $catConst : null;
    }
}
