import { Injectable, Logger } from '@nestjs/common';
import { CreateImageDto } from './dto/create-image.dto';
import { UpdateImageDto } from './dto/update-image.dto';

import fs from 'fs';

@Injectable()
export class ImagesService {
	private logger = new Logger(ImagesService.name);

	create(passedImages: Array<Express.Multer.File>) {
		// var file = passedImages;
		var imageNames: Array<String> = [];
		try {
			const dateTime = new Date().valueOf();

			this.logger.log({ level: 'info', message: `Images created with new file`, refCode: '32201' });

			passedImages.forEach((file) => {
				const newHash = Math.random().toString(36).substring(7);
				var destinationPath = `${newHash}_${dateTime}.${file.mimetype.split('/')[1]}`; // create a unique name for the file

				// write the file to the destination

				fs.writeFileSync(`public/images/${destinationPath}`, file.buffer);
				imageNames.push(destinationPath);
			});
		} catch (error) {
			this.logger.error({ level: 'error', message: `Error creating images with ${JSON.stringify(imageNames)}`, refCode: '32202' });
		}
		// });

		this.logger.log({ level: 'info', message: `Images created with name ${imageNames}`, refCode: '32201' });
		return imageNames;
	}

	findAll() {
		return `This action returns all images`;
	}

	findOne(id: number) {
		return `This action returns a #${id} image`;
	}

	update(id: number, updateImageDto: UpdateImageDto) {
		return `This action updates a #${id} image`;
	}

	remove(id: number) {
		return `This action removes a #${id} image`;
	}

	uploadImage(image: File) {
		const file = image;
		const reader = new FileReader();
		reader.onload = function () {
			console.log(reader.result);
		};
		reader.readAsDataURL(file);
	}
}
