const {app, remote} = require('electron');
const log = require('electron-log');
const fs = require('fs');
const path = require('path');

const heshChecker = require('../hesh-checker');

const get = (newData) => {
    try {
        const toDownload = new Map();
        const result = [];
        const userDataPath = app.getPath('userData');

        if ( !newData || newData.length < 1 ) {
            return result;
        }

        newData.forEach((dataItem, dataItemIndex) => {
            if ( dataItem._id && dataItem.script && dataItem.script.length > 0 ) {
                dataItem.script.forEach((script, scriptIndex) => {
                    script.script_content.forEach((contentItem, srcIndex) => {
                        contentItem.content_server_path.forEach((contentServerPath, itemIndex) => {
                            toDownload.set(contentItem.content_server_path[itemIndex], contentItem.content_hash[itemIndex]);
                        });
                    });
                });
            }
        });

        toDownload.forEach((hesh, contentPath) => {
            const itemFullPath = path.join(userDataPath, contentPath);
            const isExistsContent = fs.existsSync(itemFullPath);
            const isFoundHash = heshChecker.find(contentPath, hesh);
            let reCheckedHash = false;

            if ( isExistsContent && !isFoundHash ) {
                reCheckedHash = heshChecker.check(contentPath, hesh);
            }

            if ( isExistsContent && reCheckedHash ) {
                heshChecker.save(contentPath, hesh);
                log.info(`item: ${contentPath} exist and Re-check hash successfully.`);

                return;
            }

            if ( isExistsContent && !isFoundHash && !reCheckedHash ) {
                fs.rmSync(itemFullPath);
                log.warn(`item: ${contentPath} found, but re-check hash failed. Item removed`);
            }

            if ( isExistsContent && isFoundHash ) {
                log.info(`item: ${contentPath} exist and hash checked successfully`);
            } else {
                result[result.length] = {
                    path: contentPath,
                    hesh: hesh
                };
            }
        });

        log.info('get items for download successfully', result);

        return result;
    } catch (e) {
        log.error('mod:content-loader/get-items-for-download broken', e);
    }
};

module.exports = get;