<?php
// Copyright (c) Pickware GmbH. All rights reserved.
// This file is part of software that is released under a proprietary license.
// You must not copy, modify, distribute, make publicly available, or execute
// its contents or parts thereof without express permission by the copyright
// holder, unless otherwise permitted by law.

namespace Shopware\Plugins\ViisonShippingCommon\Classes\Types;

use InvalidArgumentException;

class Weight
{
    const UNIT_FACTORS = [
        'mg' => 1E-6, // 1 mg = 1E-6 kg
        'g' => 1E-3,
        'kg' => 1E0,
        't' => 1E3,
    ];

    /**
     * @var float
     */
    private $valueInBasicSiUnit;

    /**
     * @param float $value
     * @param string $unit
     */
    public function __construct($value, $unit)
    {
        $this->valueInBasicSiUnit = $value * self::getUnitFactor($unit);
    }

    /**
     * @param string $unit
     * @return float
     */
    public function convertTo($unit)
    {
        return $this->valueInBasicSiUnit / self::getUnitFactor($unit);
    }

    /**
     * @param string $unit
     * @return float
     */
    private static function getUnitFactor($unit)
    {
        if (!array_key_exists($unit, self::UNIT_FACTORS)) {
            throw new InvalidArgumentException(sprintf(
                '%s is not a valid unit for %s.',
                $unit,
                self::class
            ));
        }

        return self::UNIT_FACTORS[$unit];
    }
}
