<?php

namespace IZON\Thumber\ImageResizer\Strategies;

use IZON\Thumber\Image\IImageSize;
use IZON\Thumber\Image\ImageSize;
use IZON\Thumber\ImageResizer\IImageResizerStrategy;

/**
 * CoverImageResizerStrategy computes cover size of image
 *
 * @author lukas
 */
class CropImageResizerStrategy implements IImageResizerStrategy {

    public static function getSize(IImageSize $imageSize, IImageSize $containerSize, bool $upsize = false): IImageSize {
        if($upsize) {
           return $containerSize; 
        }
        if($imageSize->getAspectRatio() > 1) { // width is smaller
            if($containerSize->getWidth() > $imageSize->getWidth()) {
                $width = $imageSize->getWidth();
            } else {
                $width = $containerSize->getWidth();
            }
            $height = (int) floor($width * $containerSize->getAspectRatio());
            if($height > $imageSize->getHeight()) {
                $height = $imageSize->getHeight();
                $width = (int) floor($height / $containerSize->getAspectRatio());
            }
        } else { // height is smaller
            if($containerSize->getHeight() > $imageSize->getHeight()) {
                $height = $imageSize->getHeight();
            } else {
                $height = $containerSize->getHeight();
            }
            $width = (int) floor($height / $containerSize->getAspectRatio());
            if($width > $imageSize->getWidth()) {
                $width = $imageSize->getWidth();
                $height = (int) floor($width * $containerSize->getAspectRatio());
            }
        }

        return ImageSize::create($width, $height);
    }

}

