<?php

namespace Comitium5\DesignerBundle\Manager\Asset;

use Comitium5\DesignerBundle\ValueObjects\Asset\CordsObject;
use Comitium5\DesignerBundle\ValueObjects\Common\SizableObject;

/**
 * Class CordsManager
 *
 * @author Carles Gómez <carles@bab-soft.com>
 * @package Comitium5\DesignerBundle\Manager\Asset
 */
class CordsManager
{
    /**
     * @param SizableObject $image
     * @param SizableObject $crop
     *
     * @return CordsObject
     */
    public function generateCords(SizableObject $image, SizableObject $crop): CordsObject
    {
        $ratio = $this->calculateRatio($crop);
        $ratioImage = 1;

        if ((int) $image->getHeight() > 0) {
            $ratioImage = $image->getWidth() / $image->getHeight();
        }

        $cx = $image->getWidth() / 2;
        $cy = $image->getHeight() / 2;

        if ($ratio >= $ratioImage) {
            $wc = $image->getWidth();
            $hc = $image->getWidth() / $ratio;
        } else {
            $wc = $image->getHeight() * $ratio;
            $hc = $image->getHeight();
        }

        $x = $cx - ($wc / 2);
        $y = $cy - ($hc / 2);

        return new CordsObject($x, $y, $wc, $hc);
    }

    /**
     * @param SizableObject $crop
     *
     * @return float|int
     */
    public function calculateRatio(SizableObject $crop)
    {
        return $crop->getWidth() / $crop->getHeight();
    }
}
