const path = require('path');
const fs = require('fs');
const log = require('electron-log');

const getSavedData = require('./jsondata/get-local-data');
const getParams = require('./get-params');

module.exports = async () => {
    const {appUserData, savedDataPath, uploadsPath} = await getParams('appUserData', 'savedDataPath', 'uploadsPath');

    getSavedData(savedDataPath)
        .then((dataFileNames) => {
            const savedFilesPaths = new Set();

            for ( const filename in dataFileNames ) {
                if ( !dataFileNames[filename] ) {
                    return false;
                }

                const filePath = path.join(savedDataPath, dataFileNames[filename]);

                if ( !fs.existsSync(filePath) ) {
                    return log.error('module:content-cleaner', 'file '+ filePath +' not exists!');
                }

                const data = JSON.parse(fs.readFileSync(filePath));

                data.forEach((dataItem) => {
                    if ( dataItem && dataItem.script && dataItem.script.script_content ) {
                        dataItem.script.script_content.forEach((contentItem) => {
                            if ( contentItem.content_server_path ) {
                                savedFilesPaths.add(path.join(appUserData, contentItem.content_server_path));
                            }
                        });
                    }
                });
            }

            // log.error(savedFilesPaths);

            const cleaner = function (uploadsPath) {
                fs.readdir(uploadsPath, function(err, filenames) {
                    if (err) {
                        return log.error('module:content-cleaner fs.readdir('+ uploadsPath +')');
                    }

                    filenames.forEach(function(filename) {
                        const thisFilePath = path.join(uploadsPath, filename);

                        if ( path.parse(thisFilePath).ext ) {
                            if ( !savedFilesPaths.has(thisFilePath)) {
                                log.error('remove file '+ thisFilePath);
                                fs.unlinkSync(thisFilePath);
                            }
                        } else {
                            cleaner(thisFilePath);
                        }
                    });

                });
            };

            cleaner(uploadsPath);
        })
        .catch((err) => {
            log.error('module:content-cleaner getSavedData rejected!', err);
        });
};
