<?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\ObjectContext;
use idoit\Module\SyneticsFlows\Automation\Trigger\TriggerType\ButtonTriggerType;
use idoit\Module\SyneticsFlows\Automation\TriggerService;
use isys_component_template;
use isys_module_synetics_flows;
use Symfony\Component\Console\Command\Command;

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

    public function __invoke(string $type, array $pageData): void
    {
        if (!isys_module_synetics_flows::isLicensed()) {
            return;
        }

        $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;
        }

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

        foreach ($flows as $flow) {
            if ($flow->getTrigger() instanceof ButtonTriggerType) {
                $buttons[] = [
                    'trigger' => [
                        'name' => $flow->getTrigger()->getName(),
                    ],
                    '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);
    }
}
