// crop idea by https://stackoverflow.com/users/266531/kirby
var mouse_down_event;

var crop_selection = editor_obj.add_rect(null, true, canvas.width, canvas.height, 200, 200, "transparent", "#ccc", "crop");
crop_selection.visible = false;
crop_selection.colorable = false;
crop_selection.strokeDashArray = [2, 2];

canvas.on("mouse:down", function(e) {
    crop_selection.visible = false;
    if(!canvas.getActiveObject() && typeof crop_selection != "undefined" && document.getElementById("selection").classList.contains("top-menu-button-selected")) {
        crop_selection.width = 2;
        crop_selection.height = 2;
        crop_selection.left = canvas.getPointer(e.e).x;
        crop_selection.top = canvas.getPointer(e.e).y;
        mouse_down_event = {
            x: canvas.getPointer(e.e).x,
            y: canvas.getPointer(e.e).y,            
        };
        canvas.bringToFront(crop_selection);
    }
});

canvas.on("mouse:move", function(e) {
    if(mouse_down_event && typeof crop_selection != "undefined" && document.getElementById("selection").classList.contains("top-menu-button-selected")) {        
        var crop_deltaX = canvas.getPointer(e.e).x - mouse_down_event.x;
        var crop_deltaY = canvas.getPointer(e.e).y - mouse_down_event.y;      
        crop_selection.width = Math.abs(crop_deltaX);
        crop_selection.height = Math.abs(crop_deltaY);

        if(crop_deltaX < 0){
            crop_selection.left = mouse_down_event.x + crop_deltaX;
        }
        if(crop_deltaY < 0){
            crop_selection.top = mouse_down_event.y + crop_deltaY;             
        }
       
        crop_selection.scaling = true;
        if(crop_selection.width > 10){
            crop_selection.visible = true;            
        }
        canvas.renderAll();
    }
});

canvas.on("mouse:up", function() {
    mouse_down_event = null;
    if(crop_selection.visible){
        crop_selection.added = true;
        crop_selection.scaling = false;
        showPoupup(crop_selection, "4");
        setTimeout(function(){
            crop_selection.setCoords();
            canvas.setActiveObject(crop_selection, undefined);
            canvas.renderAll();        
        }, 10)        
    }
});
document.getElementById('cut').addEventListener('click', function() {
    var image = canvas.backgroundImage;
    image.selectable = true;
    crop_selection.visible = false;

    var transform = fabric.util.transformPoint(new fabric.Point(crop_selection.left, crop_selection.top), canvas.viewportTransform);   
    var x = transform.x;
    var y = transform.y; 

    src = canvas.toDataURL({
        copy: true,
        multiplier: 1 / global_zoom,
        left: x,
        top: y,
        width: crop_selection.width * global_zoom,
        height: crop_selection.height * global_zoom
    });
    
    editor_obj.add_image(src, true);
});