<?php

namespace common\logic\Config\Unit\Service;

use common\logic\AbstractSolver;

class UnitSolver extends AbstractSolver
{
    protected UnitDefinition $unitDefinition;

    public function loadDependencies(): void
    {
        $this->unitDefinition = $this->loadService(UnitDefinition::class);
    }

    public function getUnit(string $idUnit): ?array
    {
        $unitsArray = $this->unitDefinition->getUnits();
        if(isset($unitsArray[$idUnit])) {
            return $unitsArray[$idUnit];
        }

        return null;
    }

    // getRefUnit
    public function getUnitReference(string $idUnit): string
    {
        $unit = $this->getUnit($idUnit);

        if ($unit && isset($unit['ref_unit'])) {
            return $unit['ref_unit'];
        }

        return $idUnit;
    }

    public function getUnitCoefficient(string $idUnit): int
    {
        $unit = $this->getUnit($idUnit);

        if($unit) {
            return $unit['coefficient'];
        }

        return 1;
    }

    /**
     * Retourne le libellé d'une unité.
     */
    public function strUnit(string $idUnit, $format = UnitDefinition::WORDING_SHORT, bool $unitReference = false): string
    {
        if ($unitReference) {
            $idUnit = $this->getUnitReference($idUnit);
        }

        $unit = $this->getUnit($idUnit);
        if ($unit && isset($unit[$format])) {
            return $unit[$format];
        }

        return '';
    }
}