const fs = require('fs');
const path = require('path');
const PosterImage = require('./PosterImage');
const LoadImgToBlob = require('./LoadimgToBlob');
const imageConfig = require ('../../config/image.json');

async function clearDirectory(directoryPath) {
    try {
        // Pobierz listę plików i folderów w katalogu
        const files = fs.readdirSync(directoryPath);

        // Usuń każdy plik lub folder
        for (const file of files) {
            const fullPath = path.join(directoryPath, file);
            fs.unlinkSync(fullPath);
        }

        console.log(`Zawartość katalogu ${directoryPath} została usunięta.`);
    } catch (error) {
        if (error.code === 'ENOENT') {
            console.log(`Katalog ${directoryPath} nie istnieje.`);
        } else {
            console.error(`Błąd podczas usuwania zawartości katalogu: ${error.message}`);
        }
    }
}

async function UploadImageFromFile(req, res) {
    try {
        if(!req.session.isLogged) {
            console.error('DESCRYPTION ERROR: Urzytkownik nie jest zalogowany');
            return res.status(401).json(null);
        }

        if (!req.files || !req.files.file) {
			console.error('')
            return res.status(400).json({ error: 'No file uploaded' });
        }

        const uploadPath = path.join(__dirname, `../../upload/${req.session.user_hash}/raw`);
		console.log(uploadPath);
        fs.mkdirSync(uploadPath, { recursive: true });

        await clearDirectory(uploadPath);

        const uploadedFile = req.files.file;
        const fileExtension = path.extname(uploadedFile.name); // np. ".jpg"

        const newFileName = `raw-uploaded-image${Date.now()}${fileExtension}`;
        const filePath = path.join(uploadPath, newFileName);

        await uploadedFile.mv(filePath);

        const posterPath = await PosterImage(filePath, req.session.user_hash);
        req.session.img_files = posterPath;

        //Wczytaj grafikę i przekonwertuj na BASE64
        const blob = await LoadImgToBlob(posterPath.poster);
        const b64 = `data:image/${imageConfig.type};base64,${Buffer.from(blob).toString('base64')}`;

        res.status(200).json({
            message: 'File uploaded successfully',
            url: b64
        });
    }
    catch(e) {
        console.error(`ERROR UPLOAD FILE #2: \n ${e}`);
        res.status(500).json({
            success: false,
            mess: 'Nie udało się przesłać grafiki'
        });
    }
}

module.exports = UploadImageFromFile;