<?php

namespace IZON\Thumber\Utils;

use IZON\Thumber\Exceptions\ThumberException;

/**
 * Description of CropPositionConvertor
 *
 * @author lukas
 */
class CropPositionConvertor {

    private const PERCENT_REGEX = '#^100%$|^[0-9]{1,2}%$#';
    
    private const WIDTH_RANGE = [
        'left' => '0%',
        'center' => '50%',
        'right' => '100%'
    ];
    
    private const HEIGHT_RANGE = [
        'top' => '0%',
        'center' => '50%',
        'bottom' => '100%'
    ];
    
    public static function convert($cropPosition, $side = 'width') : float {
        if($side == 'width') {
            $sideArray = self::WIDTH_RANGE;
        } else if($side == 'height') {
            $sideArray = self::HEIGHT_RANGE;
        } else {
            throw new ThumberException("Unsupported side '$side'");
        }
        if(array_key_exists($cropPosition, $sideArray)) {
            $cropPosition = $sideArray[$cropPosition];
        }
        $percents = self::parsePercent($cropPosition);
        return $percents / 100;
    }
    
    protected static function parsePercent($value) : int {
        $status = preg_match(self::PERCENT_REGEX, $value);
        if($status !== 1) {
            throw new ThumberException("Could not parse percent value '$value'");
        } 
        return (int) substr($value, 0, -1);
    }
    
    
}
