//get folders of images to use as classes
const glob = require('glob');
const library = require('image-classifier');
const fs = require('fs');
// const 
const path = require('path')
const cliProgress = require('cli-progress');
const multer = require('multer');
const express = require('express');
const tesseract = require('node-tesseract');
const app = express();

const upload = multer({
    dest: './temp',
    
})

app.post('/classify', upload.single("file"), (req, res) => {
    const tempPath = req.file.path;
    console.log(tempPath);
    classifier.predict(tempPath).then(async (result) => {
        const readable = ['VIN', 'Data Plates', 'Dash Number', 'Door Tag'];
        if(readable.includes(result.label)){
            tesseract.process(path.resolve(__dirname, tempPath),{},  async (err, text) => {
                result.processedText = text;
                if(err) {
                    console.error('Error:', err);
                }

                await fs.unlink(tempPath, (err) =>{ if(err) console.error('Unlink Error:', err)});
                res.status(200).json(result);
            })
        } else {
            console.log('Not readable, continuing');
            await fs.unlink(tempPath, (err) =>{ if(err) console.error('Unlink Error:', err)});
            res.status(200).json(result);
        }

        // tesseract.process(tempPath, function(err, text) => {
        //     console.log()
        // })


    })
    // res.status(200).json({message: 'Success'})
})
app.listen(2666);

var shouldRebuildModel = false;

process.argv.forEach((val, index, array) => {
    console.log(val)
    if(val === '--rebuild'){
        shouldRebuildModel = true;
    }

})


function getClass(file) {
    return path.dirname(file).split('/').pop();
}
function pGlob(pattern) {
    return new Promise((resolve, reject) => {
        glob(pattern, (error, matches) => {
            if(error) return reject(error);
            resolve(matches);
        })
    })
}
var classifier;

async function runAsync() {

    if(shouldRebuildModel) {
        classifier = await library.create();

        const matches = await pGlob('training images/**/*');
        const startTime = new Date().getTime();
        console.log(`Building model with ${matches.length} training items...`)
        const rebuildBar = new cliProgress.SingleBar({}, cliProgress.Presets.shades_grey);
        rebuildBar.start(matches.length);
        await Promise.all(matches.map(file => {
            if(fs.lstatSync(file).isDirectory()) {
                rebuildBar.increment();
                return Promise.resolve();
            }
            const classA = getClass(file);
            return classifier.addExample(classA, file).then(() => rebuildBar.increment())
        })).catch(error => {
            console.error(error);
        });
        rebuildBar.stop();
        console.log('all examples loaded...');
        console.log('saving dataset...')
        await classifier.save('./export.json');
        const now = new Date().getTime();

        const elapsed = now - startTime;
        console.log(`Time to build: ${elapsed / 1000}s`)
    } else {
        classifier = await library.load('./export.json');
    }
    // const matches = await pGlob('test images/**/*');
    // const classifyBar = new cliProgress.SingleBar({}, cliProgress.Presets.shades_grey);
    // classifyBar.start(matches.length);
    // await Promise.all(matches.map(async file => {
    //     const baseFileName = path.parse(file).name;
    //     const extension = path.extname(file);
    //     const newClass= await classifier.predict(file);
    //     // console.log(newClass);
    //     return new Promise((resolve, reject) => {
    //         if(!fs.existsSync(path.resolve('sorted images', newClass.label))){
    //             fs.mkdirSync(path.resolve('sorted images', newClass.label));
    //         }
    //         fs.copyFile(file, path.resolve('sorted images', newClass.label, `${baseFileName}.${extension}`), () => {
    //             classifyBar.increment();
    //             resolve()
    //         });
    //     })
    // }))  
    // classifyBar.stop();
}
runAsync();

