"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const jquery_1 = __importDefault(require("jquery"));
const Upload_1 = __importDefault(require("./Upload"));
class UploadAndCropper extends Upload_1.default {
    static create(props) {
        return new UploadAndCropper(props);
    }
    constructor(props) {
        super(props);
        this.on('dropzone.accept', (width, height) => {
            this.initCropper(width, height);
        });
        this.on('modal.hide', () => {
            this.destroyCropper();
        });
    }
    handleDropzoneSending(formData) {
        const cropper = (0, jquery_1.default)(this.getPreviewImage());
        // @ts-ignore
        const imageData = cropper.cropper('getData');
        formData.append('p_x', imageData.x);
        formData.append('p_y', imageData.y);
        formData.append('p_w', imageData.width);
        formData.append('p_h', imageData.height);
    }
    initCropper(naturalWidth, naturalHeight) {
        this.setUploadShow(false);
        this.setPreviewShow(true);
        const img = (0, jquery_1.default)(this.getPreviewImage());
        const w = img.width() || 0;
        const h = img.height() || 0;
        // @ts-ignore
        this.$cropper = img.cropper({
            viewMode: 1,
            aspectRatio: this.props.size.width / this.props.size.height,
            zoomable: false,
            minCropBoxWidth: this.props.size.width * w / naturalWidth,
            minCropBoxHeight: this.props.size.height * h / naturalHeight,
            ready: function () {
                const imageData = this.cropper.getImageData();
                const canvasData = this.cropper.getCanvasData();
                const halfWidth = 2;
                this.cropper.setCropBoxData({
                    top: canvasData.top,
                    left: (canvasData.width - imageData.width) / halfWidth,
                    height: imageData.height
                });
            }
        });
    }
    destroyCropper() {
        if (this.$cropper) {
            this.$cropper.cropper('destroy');
        }
    }
}
exports.default = UploadAndCropper;
