import {Component, Output, EventEmitter, Input, OnInit} from '@angular/core';
import {Subscription} from 'rxjs';
import {FileService} from "./file.service";
import {Observable} from "rxjs";

@Component({
    selector: 'file-uploader',
    templateUrl: './file-uploader.component.html',
    styleUrls: ['./file-uploader.component.css'],
    inputs: ['activeColor', 'baseColor', 'overlayColor']
})
export class FileUploaderComponent implements OnInit {

    @Output('imagenes') img_emitter: EventEmitter<any[]> = new EventEmitter(true);
    activeColor: string = 'green';
    baseColor: string = '#ccc';
    grayColor: string = '#a2a2a2';
    overlayColor: string = 'rgba(255,255,255,0.5)';
    dato = [];
    dragging: boolean = false;
    loaded: boolean = false;
    imageLoaded: boolean = false;
    imageSrc: string = '';
    iconColor: any = '';
    borderColor: any = '';
    subscription: Subscription;
    @Input('srcImage') srcImage: string = null;
    @Input('msg') msg: string = null;
    listadoImagenes: Observable<Array<any>>;

    constructor(private _fileService: FileService) {
        this.subscription = _fileService.imageSourceAnnounced$.subscribe(
            img => {
                //this.imageSrc = img + '?' + moment(new Date).format('HH:mm');
                this.imageSrc = '';
            });
    }

    ngOnInit(): void {
        //console.log('imgsrc', this.srcImage);
        if (this.srcImage) {
            this.imageSrc = this.srcImage;
        }
    }

    handleDragEnter() {
        this.dragging = true;
    }

    handleDragLeave() {
        this.dragging = false;
    }

    handleDrop(e) {
        e.preventDefault();
        this.dragging = false;
        this.handleInputChange(e);
    }

    handleImageLoad() {
        this.imageLoaded = true;
        this.iconColor = this.overlayColor;
    }

    handleInputChange(e) {
        this.dato = [];
        var files = e.dataTransfer ? e.dataTransfer.files : e.target.files;
        var pattern = /image-*/;
        var reader = new FileReader();


        this.listadoImagenes = new Observable(observer => {
            for (let file of files) {
                observer.next(file);
            }
            observer.complete();
        });

        this.listadoImagenes.subscribe((file: any) => {
            //console.log('Imagen =>>>>>>', file);
            if (!file.type.match(pattern)) {
            	alert('El archivo que trata de subir no es una imagen')
                return;
            }

            this.loaded = false;
            //reader.onload = this._handleReaderLoaded.bind(this);
            //reader.readAsDataURL(file);
            var reader = new FileReader();
            this.readFile(file, reader, (result) => {
                //this.imageSrc = result;
                this.loaded = true;
                this.dato.push({
                    image: result,
                    deUrlFoto: file.name,
                    size: file.size,
                    type: file.type,
                    bandera: 0,
                    message: ''
                });
            });
        },
        error=>{
            //console.log('ERROR =>>>>', error);
        },
        () => {
            setTimeout(() => {
                this.img_emitter.emit(this.dato);
            }, 1000);
        });




    }

    readFile(file, reader, callback) {
        // Set a callback funtion to fire after the file is fully loaded
        reader.onload = () => {
            // callback with the results
            callback(reader.result);
        }

        // Read the file
        reader.readAsDataURL(file);
    }

    _handleReaderLoaded(e) {
        console.log("I => ", e);
        var reader = e.target;
        this.imageSrc = reader.result;
        this.loaded = true;
    }

    _setActive() {
        this.borderColor = this.activeColor;
        if (this.imageSrc.length === 0) {
            this.iconColor = this.activeColor;
        }
    }

    _setInactive() {
        this.borderColor = this.baseColor;
        if (this.imageSrc.length === 0) {
            this.iconColor = this.baseColor;
        }
    }

}
