/* eslint-disable max-depth */
/* eslint-disable complexity */
import Jimp from 'jimp'
import fs from 'fs/promises'
import crypto from 'crypto'
import path from 'path'

/**
 *
 *
 * @param path the folder to search
 *
 * @return the list of files included in this folder/subfolders
 */
async function filesList(Path: string): Promise<Array<string>> {
	const files: Array<string> = []
	const subFolders = await fs.readdir(Path)
	for await (const subFolder of subFolders)
	{
		const stats = await fs.stat(Path + '/' + subFolder)
		if (stats.isDirectory()) {
			files.push(...await filesList(Path + '/' + subFolder))

		} else {
			files.push(Path + '/' + subFolder)
		}

	}
	return files
}

(async (dirPath: string) => {
	// eslint-disable-next-line @typescript-eslint/no-var-requires
	const files = await filesList(dirPath)
	console.log(files)
	// Filtre cool
	const imageFiles = (await files).filter((file) => file.endsWith('.jfif'))
	const data = (await fs.readFile('./output.json')).toString('utf8')

	let json: Record<string, string> = {}
	try{
		json = JSON.parse(data)

	}catch{
		console.log('handeling...')
	}


	console.log('previous entries', json)


	for await (const file of imageFiles) {

		const hash = crypto.createHash('sha256')
		hash.setEncoding('hex')
		const readI = await fs.readFile(`${file}`)
		hash.write(readI)
		hash.end()
		const sha256sum = hash.read()

		if (json[file] === sha256sum) {
			console.log('This picture has already been turned to sepia')
			continue
		}

		// Modification des données
		json[file] = sha256sum

		console.log('current entries', json)

		// Ré-écriture dans le fichier output
		await fs.writeFile('output.json', JSON.stringify(json))

		const image = await Jimp.read(readI)
		// read image
		image.sepia()
		// change name
		const bFile = path.basename(file)
		const pName = path.dirname(file)
		console.log(bFile)
		const newFileName = pName + '/.' + bFile
		console.log('newfilename:' + newFileName)
		// save image with new file name
		await image.writeAsync(`${newFileName}`)
		console.log('Images have been inverted and rename ' + '.' + file)
	}

})('./images')
