"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const dropzone_1 = __importDefault(require("dropzone"));
const Form_1 = require("../../Form");
const Modal_1 = __importDefault(require("../../Modal"));
const EventEmitter = require('events');
dropzone_1.default.autoDiscover = false;
class Upload extends EventEmitter {
    static create(props) {
        return new Upload(props);
    }
    constructor(props) {
        super();
        this.props = props;
    }
    openModal() {
        this.setModalShow(true);
    }
    makeModal() {
        const body = '<div class="upload-container form-group"><div class="col-xs-12">' +
            '   <form class="dropzone"><div class="dz-default dz-message"><span>Перетягніть зображення сюди <span>або НАТИСНІТЬ</span></span></div></form>' +
            `   <div class="help-block">${this.props.modal.fileHelp}</div>` +
            '</div></div>' +
            '<div class="image-preview-container hide" style="height: 500px;">' +
            '       <img src="" alt="" style="max-width: 100%;">' +
            '</div>';
        const footer = `<button type='button' class='btn btn-primary btn-ladda ladda-button' data-style='expand-left' data-spinner-size='20' disabled>
            <span class='ladda-label'>${this.props.modal.button.action}</span>
            </button>
            <button type='button' class='btn btn-default' data-dismiss='modal'>${this.props.modal.button.close}</button>`;
        Modal_1.default.open(this.props.modal.title);
        Modal_1.default.setBody(body);
        Modal_1.default.setFooter(footer);
        Modal_1.default.onClose(() => {
            this.emit('modal.hide');
            this.destroyModal();
        });
        this.submitBtnRef = Modal_1.default.getFooter().find('.ladda-button').get(0);
        this.uploadContainerRef = Modal_1.default.getBody().find('.upload-container').get(0);
        this.previewContainerRef = Modal_1.default.getBody().find('.image-preview-container').get(0);
    }
    setModalShow(show) {
        if (show) {
            this.makeModal();
            this.initDropzone();
            this.emit('modal.show');
        }
        else {
            Modal_1.default.close();
        }
    }
    setUploadShow(show) {
        this.uploadContainerRef.classList.toggle('hide', !show);
    }
    setPreviewShow(show) {
        this.previewContainerRef.classList.toggle('hide', !show);
    }
    setButtonLoading(buttonLoading) {
        if (buttonLoading) {
            if (this.submitBtnLaddaRef == null) {
                this.submitBtnLaddaRef = Form_1.Ladda.create(this.submitBtnRef);
            }
            this.submitBtnLaddaRef.start();
        }
        else if (this.submitBtnLaddaRef) {
            this.submitBtnLaddaRef.stop();
        }
    }
    setButtonDisabled(disabled) {
        this.submitBtnRef.disabled = disabled;
    }
    initDropzone() {
        this.dropzone = new dropzone_1.default(this.uploadContainerRef.querySelector('form'), {
            url: this.props.modal.url,
            paramName: 'p_file',
            maxFilesize: this.props.modal.maxFilesize,
            maxFiles: 1,
            autoProcessQueue: false,
            acceptedFiles: 'image/*',
            accept: (file, done) => this.handleDropzoneAccept(file, done)
        });
        this.dropzone.on('sending', (file, xhr, formData) => this.handleDropzoneSending(formData));
        this.dropzone.on('canceled', () => this.handleDropzoneCanceled());
        this.dropzone.on('success', (file, data) => this.handleDropzoneSuccess(file, data));
        this.submitBtnRef.addEventListener('click', () => this.runProcessUpload());
    }
    handleDropzoneRemoveAllFiles() {
        this.dropzone.removeAllFiles(true);
    }
    handleDropzoneAccept(file, done) {
        this.getDataUrl(file, (dataUrl) => {
            this.previewFile(dataUrl, (width, height) => {
                if (width < this.props.size.width || height < this.props.size.height) {
                    done();
                    this.handleDropzoneRemoveAllFiles();
                    alert(this.props.size.alert);
                }
                else {
                    this.setButtonDisabled(false);
                    this.emit('dropzone.accept', width, height);
                    done();
                }
            });
        });
    }
    handleDropzoneSending(formData) {
    }
    handleDropzoneCanceled() {
        this.setButtonLoading(false);
        this.handleDropzoneRemoveAllFiles();
        alert('При завантаженні сталася помилка');
    }
    handleDropzoneSuccess(file, data) {
        this.setButtonLoading(false);
        if (data.ok && data.image_id) {
            this.setModalShow(false);
            this.emit(Upload.EVENT_uploadSuccess, file, data.image_id);
        }
        else if (data.msg) {
            this.handleDropzoneRemoveAllFiles();
            alert(data.msg);
        }
        else {
            this.handleDropzoneRemoveAllFiles();
            alert('При завантаженні сталася помилка');
        }
    }
    getPreviewImage() {
        return this.previewContainerRef.querySelector('img');
    }
    destroyModal() {
        this.setUploadShow(true);
        this.setPreviewShow(false);
        this.setButtonDisabled(true);
        this.dropzone.destroy();
    }
    runProcessUpload() {
        this.setButtonLoading(true);
        this.dropzone.processQueue();
    }
    getDataUrl(file, callback) {
        const reader = new FileReader();
        reader.onload = () => callback(reader.result);
        reader.readAsDataURL(file);
    }
    previewFile(dataUrl, callback) {
        const image = this.getPreviewImage();
        image.onload = () => callback(image.naturalWidth, image.naturalHeight);
        image.src = dataUrl;
    }
}
exports.default = Upload;
Upload.EVENT_uploadSuccess = 'uploadSuccess';
