class CropperModal extends Service('hn.enterprise')
    constructor: ($modal, $rootScope) ->

        ###
        For cropperOptions see:
        http://fengyuanchen.github.io/cropper/

        Example:
            cropperModalService.open({
                imageUrl: '/images/cat.jpg'
                modalTitle: 'Crop!'
                cropperOptions: {
                    autoCropArea: 0.75
                }
                onCrop: (data, closeFn) ->
                    console.log('cropped:', data)
                    closeFn()
            })
        ###

        @open = ({imageUrl, cropperOptions, onCrop, modalTitle}) ->
            scope = $rootScope.$new()
            scope.imageId = _.uniqueId('cropper')
            scope.title = modalTitle or "Crop Image"
            scope.src = imageUrl
            image = null

            bindCropper = ->
                image.cropper(cropperOptions or {})

            scope.crop = (closeFn) ->
                data = image.cropper('getCropBoxData')
                onCrop(data, closeFn)

            promise = $modal.open(
                templateUrl: '/modules/enterprise/components/cropper_modal/cropper_modal.html'
                scope: scope
            )

            promise.rendered.then(() ->
                image = $("#"+scope.imageId)
                if image.height() > 0
                    bindCropper()
                else
                    image.on('load', bindCropper)
            )
            promise.result.catch(() ->
                image.cropper('destroy')
            )
            return promise