import {Component, ElementRef, Input, OnInit, ViewChild} from '@angular/core';
import {ImageWidget} from "../../models/ImageWidget";
import {UtilsService} from "../../../../services/utils.service";

@Component({
    selector: 'app-image-widget-configuration',
    templateUrl: './image-widget-configuration.component.html',
    styleUrls: ['./image-widget-configuration.component.css']
})
export class ImageWidgetConfigurationComponent implements OnInit {
    @Input() widget?: ImageWidget;
    @ViewChild("fileInput") fileInput?: ElementRef;
    // 300Kb
    maxSize: number = 300000;
    allowedTypes = ['image/png', 'image/svg+xml', 'image/jpg', 'image/jpeg'];


    constructor(
        private utilsService: UtilsService
    ) {
    }

    ngOnInit(): void {
    }

    handleFileSelect(evt:any) {
        evt.preventDefault()
        evt.stopImmediatePropagation();
        const files: any[] = Array.from(evt.target.files);
        const file = files[0];

        if (files && file) {
            console.info(file)
            if (file && !this.allowedTypes.some(o => o == file.type)) {
                this.utilsService.showWarnMessageTrans("IMAGE_WIDGET_CONFIGURATION.FILE_TYPE_NOT_ALLOWED");
                this.fileInput!.nativeElement.value = "";
                return
            }

            if (file && file.size > this.maxSize) {
                this.utilsService.showWarnMessageTrans("IMAGE_WIDGET_CONFIGURATION.FILE_SIZE_NOT_ALLOWED");
                this.fileInput!.nativeElement.value = "";
                return
            }

            this.widget!.src = this.utilsService.getBase64Header(file.type);
            const reader = new FileReader();
            reader.onload = this._handleReaderLoaded.bind(this);
            reader.readAsBinaryString(file);

        }
        else {
            this.utilsService.showWarnMessageTrans("IMAGE_WIDGET_CONFIGURATION.FILE_UPLOAD_ERROR")
        }
    }

    _handleReaderLoaded(readerEvt: any) {
        const binaryString = readerEvt.target.result;
        this.widget!.src = this.widget?.src + btoa(binaryString);
    }
}
