<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\MainBundle\Workflow\Helper;

use Chill\MainBundle\Entity\Workflow\EntityWorkflow;
use Symfony\Component\Workflow\Registry;

/**
 * Helps to determine the status of the EntityWorkflow.
 *
 * A "negative final" step means that the workflow has been canceled, without being formerly finalized
 */
class OpenedEntityWorkflowHelper
{
    public function __construct(private readonly Registry $registry) {}

    /**
     * Return true if the entity workflow has reached a final step.
     *
     * @return bool true if the entityworkflow has reached a final step
     */
    public function isFinal(EntityWorkflow $entityWorkflow): bool
    {
        return $entityWorkflow->isFinal();
    }

    /**
     * return true if the entity workflow has reached a final and positive step.
     *
     * If multiple steps, they are all taken into account: return true if at least one step has the metadata
     * `isFinalPositive: true`
     */
    public function isFinalPositive(EntityWorkflow $entityWorkflow): bool
    {
        if (!$this->isFinal($entityWorkflow)) {
            return false;
        }

        return $this->findFinalMark($entityWorkflow, true) ?? false;
    }

    /**
     * return true if the entity workflow has reached a final and negative step.
     *
     * If multiple steps, they are all taken into account: return true if at least one step has the metadata
     * `isFinalPositive: false`.
     */
    public function isFinalNegative(EntityWorkflow $entityWorkflow): bool
    {
        if (!$this->isFinal($entityWorkflow)) {
            return false;
        }

        return $this->findFinalMark($entityWorkflow, false) ?? false;
    }

    private function findFinalMark(EntityWorkflow $entityWorkflow, bool $expectedMark): ?bool
    {
        $workflow = $this->registry->get($entityWorkflow, $entityWorkflow->getWorkflowName());
        $marking = $workflow->getMarkingStore()->getMarking($entityWorkflow);

        foreach ($marking->getPlaces() as $place => $key) {
            $metadata = $workflow->getMetadataStore()->getPlaceMetadata($place);

            if (array_key_exists('isFinalPositive', $metadata)) {
                if ($expectedMark === $metadata['isFinalPositive']) {
                    return true;
                }
            }
        }

        return null;
    }
}
