const os = require('os');

const FSWrapper = require('@sisense-ps/fs-wrapper');

const CONSTANTS = require('./constants/WindowsConsts');
const mainAction = {
    "i": '_install',
    "r": '_remove',
    "u": '_update',
    "c": '_check',
    "h": '_help',
    "v": '_version'
};

const afterMainAction = {
    "i": '__afterCopySources',
    "r": '__afterRemoveSources',
    "u": '__afterUpdate',
    "c": '__afterCheck'
};

const beforeMainAction = {
    "i": '__beforeCopySources',
    "r": '__beforeRemoveSources',
    "u": '__beforeUpdate',
    "c": '__beforeCheck'
};
class Utils {
    static getOsType() {
        return os.type();
    }

    static parseArguments(argv) {
        return argv.slice(2).join(' ');
    }

    static parsePassedArguments(patternMatches) {
        const { COMMAND_KEYS } = CONSTANTS;

        const [key, value] = patternMatches[0].trim().split(' ');
        const normalizedKey = key.replace('-', '');
        return {
            key: normalizedKey,
            name: COMMAND_KEYS[normalizedKey].name,
            value: value || 's'
        };
    }

    static getOperationType(operationKey, prefix = 'main') {
        if (prefix === 'main') {
            return mainAction[operationKey]
        } if (prefix === 'after') {
            return afterMainAction[operationKey];
        } else {
            return beforeMainAction[operationKey];
        }
    }

    static addLeadingZero(baseNumber) {
        if (baseNumber > 10) {
            return baseNumber;
        }

        return `0${baseNumber}`;
    }

    static sleep(milliseconds) {
        return new Promise((resolve) => {
            setTimeout(() => {
                resolve(true);
            }, milliseconds);
        })
    }

    static searchCommand(prms) {
        const { COMMAND_KEYS } = CONSTANTS;
        let pattern = [];

        Object.keys(COMMAND_KEYS).forEach((commandKey) => {
            const posibleValues = COMMAND_KEYS[commandKey].values.join(',');
            pattern.push(`(-[${commandKey}]{1}\\s[${posibleValues}]{1})|(^-[${commandKey}]{1}$)`);
        });

        return prms.match(new RegExp(pattern.join('|')));
    }

    static extractAddonName() {
        return FSWrapper.getRootPath()
            .split(FSWrapper.getPlatformSeparator())
            .pop()
            .match(new RegExp(CONSTANTS.PLUGIN_NAME_REGEX))[0]
            .replace(new RegExp('\\.', 'g'), '')
    }
}

module.exports = Utils;
