//our root app component
import {ChangeDetectorRef, Component, EventEmitter, Input, Output} from '@angular/core'
import {UploaderOriginalService} from './uplader-original.service';
import {Subscription} from 'rxjs';

@Component({
	selector: 'app-uploader-original',
	template: `
		<div class="col-md-12">
			<input type="file" (change)="fileChange(input)" accept="image/x-png,image/gif,image/jpeg" #input/>
		</div>
		<div class="col-md-6" *ngFor="let file_src of file_srcs; let i = index">
			<img class="img-responsive" [attr.src]='file_src' alt=""/>
		</div>
	`,
})

export class UploaderOriginalComponent {
	public file_srcs: string[] = [];
	@Output('imagenes') img_emitter: EventEmitter<any> = new EventEmitter(true);
	@Input('files_count') files_count: number = 1;
	@Input('imagen') img_src: string;
	@Input('ruta') ruta_url: string;
	subscription: Subscription;

	constructor(private changeDetectorRef: ChangeDetectorRef, private _upladerService: UploaderOriginalService) {
		this.subscription = _upladerService.imageSourceAnnounced$.subscribe(
			img => {
				if (img != null) {
					this.file_srcs.push(this.ruta_url + img);
				}
			});
	}


	// The next two lines are just to show the resize debug
	// they can be removed
	public debug_size_before: string[] = [];
	public debug_size_after: string[] = [];

	// This is called when the user selects new files from the upload button
	fileChange(input) {
		this.file_srcs = [];
		this.readFiles(input.files);
	}

	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);
	}

	readFiles(files, index = 0) {
		if (this.files_count > this.file_srcs.length) {

			if (this.files_count >= files.length) {
				// Create the file reader
				let reader = new FileReader();
				console.log('FILES => ', files);
				// If there is a file
				if (index in files) {
					// Start reading this file
					this.readFile(files[index], reader, (result) => {
						// Create an img element and add the image file data to it
						var img = document.createElement('img');
						img.src = result;

						this.show(img, (resized_jpeg, before, after) => {
							// For debugging (size in bytes before and after)
							this.debug_size_before.push(before);
							this.debug_size_after.push(after);

							// Add the resized jpeg img source to a list for preview
							// This is also the file you want to upload. (either as a
							// base64 string or img.src = resized_jpeg if you prefer a file).
							this.file_srcs.push(resized_jpeg);
							this.img_emitter.emit(this.file_srcs);
							// Read the next file;
							this.readFiles(files, index + 1);
						});
					});
				} else {
					// When all files are done This forces a change detection
					this.changeDetectorRef.detectChanges();
				}
			} else {
				console.log('Se han seleccionado mas de lo normal');
			}
		}
	}

	show(img, callback) {
		// This will wait until the img is loaded before calling this function
		return img.onload = () => {
			console.log('img loaded');

			this._upladerService.imagenCargada = true;
			// Get the images current width and height
			var width = img.width;
			var height = img.height;

			// create a canvas object
			var canvas = document.createElement('canvas');

			// Set the canvas to the new calculated dimensions
			canvas.width = width;
			canvas.height = height;
			var ctx = canvas.getContext('2d');

			ctx.drawImage(img, 0, 0, width, height);

			// Get this encoded as a jpeg
			// IMPORTANT: 'jpeg' NOT 'jpg'
			var dataUrl = canvas.toDataURL('image/png');

			// callback with the results
			callback(dataUrl, img.src.length, dataUrl.length);
		};
	}
}
