package ru.m.puzzlez.render;

import flash.display.BitmapData;
import flash.geom.Matrix;
import flash.geom.Rectangle;

class RenderUtil {

    public static function cropImage(source:BitmapData, rect:Rectangle):BitmapData {
        var image = new BitmapData(Std.int(rect.width), Std.int(rect.height));
        var matrix = new Matrix();
        var scale = Math.max(rect.width / source.width, rect.height / source.height);
        matrix.scale(scale, scale);
        matrix.translate((rect.width - source.width * scale) / 2, (rect.height - source.height * scale) / 2);
        image.draw(source, matrix);
        return image;
    }

    public static function cropImagePart(source:BitmapData, gridX:Int, gridY:Int, rect:Rectangle):BitmapData {
        var rect = new Rectangle(rect.width * gridX, rect.height * gridY, rect.width, rect.width);
        var image = new BitmapData(Std.int(rect.width), Std.int(rect.width));
        var matrix = new Matrix();
        matrix.translate(-rect.x, -rect.y);
        image.draw(source, matrix, null, null, null, true);
        return image;
    }

    public static function containRectangle(source:Rectangle, target:Rectangle):Rectangle {
        var s = Math.min(1, Math.min(target.width / source.width, target.height / source.height));
        var width = source.width * s;
        var height = source.height * s;
        return new Rectangle((target.width - width) / 2, (target.height - height) / 2, width, height);
    }
}
