import express from 'express'
import path from 'path'
import fs from 'fs/promises'
import Jimp from 'jimp'
import crypto from 'crypto'
import React from 'react'
import ReactDOMServer from 'react-dom/server'

const app = express()

app.use('/assets',express.static('assets'))
/* eslint-disable max-depth */
/* eslint-disable complexity */
app.listen(3000, () => {
	console.log('The application is listening on port 3000!')
})
/**
 *
 *
 * @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
}

app.get('/program', (_req, res) => {

	(async (dirPath: string) => {
		const files = await filesList(dirPath)
		console.log(files)
		// Filtre
		const data = (await fs.readFile('./output.json')).toString('utf8')

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

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

		for await (const file of files) {
			const bFile = path.basename(file)
			const pName = path.dirname(file)
			const hash = crypto.createHash('sha256')
			hash.setEncoding('hex')
			const readI = await fs.readFile(`${file}`)
			hash.write(readI)
			hash.end()
			const sha256sum = hash.read()
			console.log('bfile = ' + bFile)

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

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

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

			try{
				const image = await Jimp.read(readI)
				image.sepia()
				console.log(bFile)
				const newFileName = pName + '/S' + bFile
				console.log('newfilename:' + newFileName)
				// save image with new file name
				await image.writeAsync(`${newFileName}`)
				console.log('Images have been turned to sepia and renamed ' + newFileName)
			}catch (err){
				console.log('this file is not an image')
			}
		}
		res.send('Pictures transformed')
		res.end()

	})('./assets')
})
function randomSort() {
	return Math.random() - 0.5
}
async function randomI(): Promise<[] | [string, string, string, string, string, string]> {
	const list = await filesList('./assets') // si moins de 6 element dans la liste  ....
	const sorted = list.sort(randomSort).slice(0, 6)
	while (sorted.length < 6 && sorted.length > 0 ) {
		const listLength = sorted.length
		sorted.push(...list.sort(randomSort).slice(0, 6 - listLength))
	}
	return sorted as []
}
app.get('/test', async (_req, res) => {
	res.send(randomI())
})
app.get('/', async (_req, res) => {
	const list = await randomI()
	if(list.length === 0 ){
		const board =
		<><style>{`
		.string{
			color: red;}
		`}</style>
		<div className='string'>
			Il n'y a pas d'image dans le fichier
		</div></>
		const rendering = ReactDOMServer.renderToString(board)
		res.send(rendering)
	}else{
		res.send(ReactDOMServer.renderToString(
			<><style>{`
		.board {
			display: grid;
			grid-template-columns: repeat(3, 1fr);
			grid-gap: 10px;
			grid-auto-rows: minmax(100px, auto);
		.row11 {
			grid-column : 1
			grid-row : 1
		}
		.row12 {
			grid-column: 2
			grid-row: 1
		}
		.row13 {
			grid-column : 3
			grid-row : 1
		}
		.row21 {
			grid-column : 1
			grid-row : 2
		}
		.row22 {
			grid-column : 2
			grid-row : 2
		}
		.row23 {
			grid-column : 3
			grid-row : 2
		}
		}`}</style>
			<div className="board">
				<div className='row11'>
					<img src={list[0]} width={620} />
				</div>
				<div className='row12'>
					<img src={list[1]} width={620} />
				</div>
				<div className='row13'>
					<img src={list[2]} width={620} />
				</div>
				<div className="row21">
					<img src={list[3]} width={620} />
				</div>
				<div className='row22'>
					<img src={list[4]} width={620} />
				</div>
				<div className='row23'>
					<img src={list[5]} width={620} />
				</div>
			</div></>
		))
	}
})
