<?php

namespace App\Service;

use App\Entity\Project;
use App\Entity\Task;
use Symfony\Component\Workflow\WorkflowInterface;

// Utilistaire pour récupérer facilement les stats de réalisation d’un projet ou d’une tâche
class TaskLifecycleManager
{
    public function __construct(
        private WorkflowInterface $taskLifecycleStateMachine,
    ) {
    }

    public function getProjectStats($entity)
    {
        if ($entity instanceof Project) {
            $project = $entity;
        } elseif ($entity instanceof Task) {
            $project = $entity->getProject();
        } else {
            throw new \RuntimeException();
        }

        $stats = [];

        $places = $this->taskLifecycleStateMachine->getDefinition()->getPlaces();
        $metas = $this->taskLifecycleStateMachine->getMetadataStore();

        if (empty($places)) {
            return $stats;
        }

        foreach ($places as $place => $id) {
            $stats[$place] = array_merge($metas->getPlaceMetadata($place), [
                'value' => 0,
                'percentage' => 0,
            ]);
        }

        $max = 0;
        foreach ($project->getTasks() as $task) {
            ++$stats[$task->getStatus()]['value'];
            ++$max;
        }

        if (0 === $max) {
            return $stats;
        }

        $stats = array_map(function ($data) use ($max) {
            $data['max'] = $max;
            $data['percentage'] = ((float) $data['value'] * 100.0) / $max;

            return $data;
        }, $stats);

        return $stats;
    }
}
