"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
const core_1 = require("@angular/core");
require("cropperjs/dist/cropper.min.css");
require("./ngx-cropper.component.css");
const Cropper = require("cropperjs");
const ngx_cropper_service_1 = require("./ngx-cropper.service");
const ngx_cropper_model_1 = require("./ngx-cropper.model");
let NgxCropperComponent = class NgxCropperComponent {
    constructor(ngxCropperService) {
        this.ngxCropperService = ngxCropperService;
        this.isShow = false;
        this.returnData = new core_1.EventEmitter();
    }
    ngOnInit() {
        // init config
        this.viewConfig = {
            url: this.config.url || null,
            maxsize: this.config.maxsize || 512000,
            title: this.config.title || 'Apply your image size and position',
            uploadBtnName: this.config.uploadBtnName || 'Upload Image',
            uploadBtnClass: this.config.uploadBtnClass || null,
            cancelBtnName: this.config.cancelBtnName || 'Cancel',
            cancelBtnClass: this.config.cancelBtnClass || null,
            applyBtnName: this.config.applyBtnName || 'Apply',
            applyBtnClass: this.config.applyBtnClass || null,
            fdName: this.config.fdName || 'file',
            aspectRatio: this.config.aspectRatio || 1 / 1,
            viewMode: this.config.viewMode || 0
        };
    }
    ngAfterViewInit() {
        //  init upload btn, after dom content loaded init down.
        setTimeout(() => {
            const dom = (this.dom = document.getElementById('inputImage'));
            this.dom.onchange = () => {
                const files = dom.files;
                if (files && files.length > 0) {
                    this.isShow = true;
                    setTimeout(() => {
                        this.initCropper();
                        const file = files[0];
                        // Only can upload image format.
                        if (!/^(image\/*)/.test(file.type)) {
                            this.returnData.emit(JSON.stringify({
                                code: 4002,
                                data: null,
                                msg: `The type you can upload is only image format`
                            }));
                            this.isShow = false;
                            return;
                        }
                        const blobURL = URL.createObjectURL(file);
                        this.fileName = file.name;
                        this.fileType = file.type;
                        this.cropper.replace(blobURL);
                    });
                }
            };
        }, 0);
    }
    /**
     * click apply event
     *
     * @returns
     * @memberof NgxCropperComponent
     */
    onApply() {
        const blob = this.dataURItoBlob(this.cropper.getCroppedCanvas().toDataURL(this.fileType));
        if (blob.size > this.viewConfig.maxsize) {
            const currentSize = Math.ceil(blob.size / 1024);
            // sent message max then size.
            this.returnData.emit(JSON.stringify({
                code: 4000,
                data: currentSize,
                msg: `The size is max than ${this.viewConfig.maxsize}, now size is ${currentSize}k`
            }));
            return;
        }
        const fd = new FormData();
        const name = this.viewConfig.fdName;
        fd.append(name, blob, this.fileName);
        const url = this.viewConfig.url;
        this.ngxCropperService.save(url, fd).subscribe((data) => {
            // return success
            this.returnData.emit(JSON.stringify({
                code: 2000,
                data,
                msg: 'The image was sent to server successly'
            }));
            // hidden modal
            this.onCancel();
        }, (error) => {
            // return error
            this.returnData.emit(JSON.stringify({
                code: 4001,
                data: null,
                msg: 'ERROR: When sent to server, something wrong, please check the server url.'
            }));
        });
    }
    /**
     * Hidden edit modal
     *
     * @memberof NgxCropperComponent
     */
    onCancel() {
        this.isShow = false;
    }
    /**
     * transfer uri to blob
     *
     * @private
     * @param {*} dataURI
     * @returns
     * @memberof NgxCropperComponent
     */
    dataURItoBlob(dataURI) {
        const byteString = window.atob(dataURI.split(',')[1]);
        const mimeString = dataURI
            .split(',')[0]
            .split(':')[1]
            .split(';')[0];
        const ab = new ArrayBuffer(byteString.length);
        const ia = new Uint8Array(ab);
        for (let i = 0; i < byteString.length; i++) {
            ia[i] = byteString.charCodeAt(i);
        }
        const bb = new Blob([ab], {
            type: mimeString
        });
        return bb;
    }
    /**
     * init cropper plugin
     *
     * @private
     * @memberof NgxCropperComponent
     */
    initCropper() {
        const cropBox = document.getElementById('cropper-image');
        this.cropper = new Cropper(cropBox, {
            aspectRatio: this.viewConfig.aspectRatio,
            autoCrop: true,
            viewMode: this.viewConfig.viewMode || 0,
            dragMode: 'move',
            guides: true,
            movable: true,
            cropBoxMovable: false,
            cropBoxResizable: false
        });
    }
};
__decorate([
    core_1.Input(),
    __metadata("design:type", ngx_cropper_model_1.NgxCropperOption)
], NgxCropperComponent.prototype, "config", void 0);
__decorate([
    core_1.Output(),
    __metadata("design:type", core_1.EventEmitter)
], NgxCropperComponent.prototype, "returnData", void 0);
NgxCropperComponent = __decorate([
    core_1.Component({
        selector: 'ngx-cropper',
        template: `
    <section class="inline-block">
      <a class="btn btn-primary" href="javascript: void(0)"
      [ngClass]="viewConfig.uploadBtnClass"
      onclick="document.getElementById('inputImage').click()">{{viewConfig.uploadBtnName}}</a>
      <input id="inputImage" type="file" class="hide" hidden>
    </section>
    <section class="crop-container" *ngIf="isShow === true">
      <div class="crop-box">
        <div class="crop-box-header">
          <h3>{{viewConfig.title}}</h3>
          <button type="button" class="crop-box-close" (click)="onCancel()">
            <span></span>
          </button>
        </div>
        <div class="crop-box-body">
          <figure style="height: 300px;">
            <img id="cropper-image" class="full-width">
          </figure>
        </div>
        <div class="crop-box-footer">
          <a class="btn btn-default" href="javascript: void(0)"
          [ngClass]="viewConfig.cancelBtnClass"  (click)="onCancel()">{{viewConfig.cancelBtnName}}</a>
          <a class="btn btn-primary" href="javascript: void(0)"
          [ngClass]="viewConfig.applyBtnClass"  (click)="onApply()">{{viewConfig.applyBtnName}}</a>
        </div>
      </div>
    </section>
  `,
        providers: [ngx_cropper_service_1.NgxCropperService]
    }),
    __metadata("design:paramtypes", [ngx_cropper_service_1.NgxCropperService])
], NgxCropperComponent);
exports.NgxCropperComponent = NgxCropperComponent;
//# sourceMappingURL=ngx-cropper.component.js.map