<?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\Form\Type\DataTransformer;

use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;
use Symfony\Component\Form\Exception\UnexpectedTypeException;

class DateIntervalTransformer implements DataTransformerInterface
{
    public function reverseTransform($value)
    {
        if (empty($value) || empty($value['n'])) {
            return null;
        }

        $string = 'P'.$value['n'].$value['unit'];

        try {
            return new \DateInterval($string);
        } catch (\Exception $e) {
            throw new TransformationFailedException('Could not transform value into DateInterval', 1542, $e);
        }
    }

    public function transform($value)
    {
        if (empty($value)) {
            return null;
        }

        if (!$value instanceof \DateInterval) {
            throw new UnexpectedTypeException($value, \DateInterval::class);
        }

        if (0 < $value->d) {
            // we check for weeks (weeks are converted to 7 days)
            if (0 === $value->d % 7) {
                return [
                    'n' => $value->d / 7,
                    'unit' => 'W',
                ];
            }

            return [
                'n' => $value->d,
                'unit' => 'D',
            ];
        }

        if (0 < $value->m) {
            return [
                'n' => $value->m,
                'unit' => 'M',
            ];
        }

        if (0 < $value->y) {
            return [
                'n' => $value->y,
                'unit' => 'Y',
            ];
        }

        throw new TransformationFailedException('The date interval does not contains any days, months or years.');
    }
}
