'use strict';

const path = require('path');
const tools = require('../tools');

let { subgroup } = tools.getArgs();


module.exports.migrate = (pkg) => {
    return Promise.resolve()
    .then(() => {

        if (!subgroup) {
            subgroup = 'myworkplace-ui';
        }     

        tools.logTitle(`Migrating package ${pkg.name} for subgroup ${subgroup}`);

        console.log(pkg);

        tools.logInfo('Replacing .csdr/packages config');

        let pkgDef = {
            "name": pkg.name,
            "npmPkg": pkg.npmPkg,
            "repository": `${subgroup}/${pkg.name}.git`,
            "sdlc": true
        };
        console.log(pkgDef);
       
        const packagesConfigFile = path.join(process.cwd(), '.csdr', '.euirc-csdr-packages.json');
        const packagesConfig = require(packagesConfigFile);

        packagesConfig[pkg.name] = pkgDef;

        tools.writeJsonFileSync(packagesConfigFile, packagesConfig);


        tools.logInfo('Adding entry in the SDLC config');
        
        pkgDef = {
            "npmPkg": pkg.npmPkg,
            "subgroup": subgroup,
            "notificationChannel": "pipeline-ui-mwp"
        };
        console.log(pkgDef);

        const packazgesSDLCConfigFile = path.join(process.cwd(), '.sdlc-config', '.euirc-packages.json');
        const packagesSDLCConfig = require(packazgesSDLCConfigFile);

        packagesSDLCConfig[pkg.name] = pkgDef;

        tools.writeJsonFileSync(packazgesSDLCConfigFile, packagesSDLCConfig);



        tools.logInfo('Adapting files for SDLC repository');

        tools.copydirFiles(path.join(__dirname, 'skeleton', 'package'), pkg.paths.root);

        tools.move(path.join(pkg.paths.root, '.gitignore_TO_REPLACE'), path.join(pkg.paths.root, '.gitignore'));



        // REMOTE CREATION

        const remotesTriggerPath = path.join(process.cwd(), 'remotes-trigger');

        if (!tools.isDirExists(remotesTriggerPath)) {
            return;
        }

        tools.logInfo('Duplicating remote config');

        const remotePrefix = `${pkg.npmPkg.split('/')[0].substr(1)}-${pkg.npmPkg.split('/')[1]}`;

        // getting eUI version for package
        const depsJson = require(path.join(pkg.paths.root, 'dependencies-composite.json'));
        const euiVersion = depsJson['@eui/deps-base'].substr(1,2);

        tools.logInfo(`eUI version found for package : ${euiVersion}`);
        

        const currentRemoteName = `${remotePrefix}-eui${euiVersion}-remote-el-ui`;
        const newRemoteName = `${remotePrefix}-remote-eui${euiVersion}`;

        console.log('Current remote : ', currentRemoteName);
        console.log('New remote : ', newRemoteName);

        const currentRemotePath = path.join(process.cwd(), 'packages', 'csdr-remotes-config', 'assets', currentRemoteName);
        const newRemotePath = path.join(process.cwd(), '.sdlc-config', 'remotes', newRemoteName);

        if (!tools.isDirExists(currentRemotePath)) {
            throw new Error(`${currentRemotePath} NOT FOUND, contact support`);
        }

        tools.copydir(currentRemotePath, newRemotePath);

        const remotesDependenciesConfigFile = path.join(process.cwd(), '.sdlc-config', 'remotes', newRemoteName, 'dependencies.json');
        const remotesDependenciesConfig = require(remotesDependenciesConfigFile);

        let remotesDependenciesConfigString = JSON.stringify(remotesDependenciesConfig);
        remotesDependenciesConfigString = remotesDependenciesConfigString.replace('"INT"', '"int"').replace('"ACC"', '"acc"').replace('"DLT"', '"dlt"').replace('"TRN"', '"trn"').replace('"PROD"', '"prd"');

        tools.writeJsonFileSync(remotesDependenciesConfigFile, JSON.parse(remotesDependenciesConfigString));

        const currentRemoteConfig = require(path.join(process.cwd(), '.csdr', '.euirc-csdr-remotes.json'))[currentRemoteName];

        const remoteSDLCConfigFile = path.join(process.cwd(), '.sdlc-config', 'remotes', '.euirc-remotes.json');
        const remotesSDLCConfig = require(remoteSDLCConfigFile);

        delete currentRemoteConfig['slack'];

        currentRemoteConfig['npmPkg'] = currentRemoteConfig['npmPkg'].replace(`eui${euiVersion}-remote-el`, `remote-eui${euiVersion}`);

        currentRemoteConfig['notificationChannel'] = 'pipeline-ui-mwp';

        currentRemoteConfig['migrated'] = true;

        remotesSDLCConfig[newRemoteName] = currentRemoteConfig;

        tools.writeJsonFileSync(remoteSDLCConfigFile, remotesSDLCConfig);
        
        
        
        
        
        tools.logInfo('Initializing remote trigger repository');
        

        tools.copydirFiles(path.join(__dirname, 'skeleton', 'remote-trigger'), path.join(remotesTriggerPath, newRemoteName));
        tools.replaceInFileSync(path.join(remotesTriggerPath, newRemoteName, '.gitlab-ci.yml'), '@module.remote.name@', newRemoteName);

        



        tools.logInfo('Importing existing medata for remote');

        const remoteMedatadataEnvs = path.join(process.cwd(), 'packages', 'devops-metadata', `${currentRemoteName}-envs-metadata.json`);

        if (!tools.isFileExists(remoteMedatadataEnvs)) {
            return;
        }

        const remoteMedatadataVersions = path.join(process.cwd(), 'packages', 'devops-metadata', `${currentRemoteName}-versions-metadata.json`);
        const remoteMedatadataHistory = path.join(process.cwd(), 'packages', 'devops-metadata', `${currentRemoteName}-history-metadata-v2.json`);

        const remoteMedatadataEnvsNew = path.join(process.cwd(), '.sdlc-metadata', `${newRemoteName}-envs-metadata.json`);
        const remoteMedatadataVersionsNew = path.join(process.cwd(), '.sdlc-metadata', `${newRemoteName}-versions-metadata.json`);
        const remoteMedatadataHistoryNew = path.join(process.cwd(), '.sdlc-metadata', `${newRemoteName}-history-metadata.json`);

        tools.copy(remoteMedatadataEnvs, remoteMedatadataEnvsNew);
        tools.copy(remoteMedatadataHistory, remoteMedatadataHistoryNew);
        tools.copy(remoteMedatadataVersions, remoteMedatadataVersionsNew);

        tools.replaceInFileSync(remoteMedatadataVersionsNew, currentRemoteName, newRemoteName);
        
        tools.replaceInFileSync(remoteMedatadataVersionsNew, '"DEV"', '"dev"');
        tools.replaceInFileSync(remoteMedatadataVersionsNew, '"TST"', '"tst"');
        tools.replaceInFileSync(remoteMedatadataVersionsNew, '"INT"', '"int"');
        tools.replaceInFileSync(remoteMedatadataVersionsNew, '"ACC"', '"acc"');
        tools.replaceInFileSync(remoteMedatadataVersionsNew, '"DLT"', '"dlt"');
        tools.replaceInFileSync(remoteMedatadataVersionsNew, '"TRN"', '"trn"');
        tools.replaceInFileSync(remoteMedatadataVersionsNew, '"PPD"', '"ppd"');
        tools.replaceInFileSync(remoteMedatadataVersionsNew, '"PROD"', '"prd"');

        tools.replaceInFileSync(remoteMedatadataVersionsNew, '-TST.', '-tst.');
        tools.replaceInFileSync(remoteMedatadataVersionsNew, '-INT.', '-int.');
        tools.replaceInFileSync(remoteMedatadataVersionsNew, '-ACC.', '-acc.');
        tools.replaceInFileSync(remoteMedatadataVersionsNew, '-DLT.', '-dlt.');
        tools.replaceInFileSync(remoteMedatadataVersionsNew, '-TRN.', '-trn.');
        tools.replaceInFileSync(remoteMedatadataVersionsNew, '-PPD.', '-ppd.');


        if (tools.isFileExists(remoteMedatadataHistoryNew)) {
            tools.replaceInFileSync(remoteMedatadataHistoryNew, '"DEV"', '"dev"');
            tools.replaceInFileSync(remoteMedatadataHistoryNew, '"TST"', '"tst"');
            tools.replaceInFileSync(remoteMedatadataHistoryNew, '"INT"', '"int"');
            tools.replaceInFileSync(remoteMedatadataHistoryNew, '"ACC"', '"acc"');
            tools.replaceInFileSync(remoteMedatadataHistoryNew, '"DLT"', '"dlt"');
            tools.replaceInFileSync(remoteMedatadataHistoryNew, '"TRN"', '"trn"');
            tools.replaceInFileSync(remoteMedatadataHistoryNew, '"PPD"', '"ppd"');
            tools.replaceInFileSync(remoteMedatadataHistoryNew, '"PROD"', '"prd"');
    
            tools.replaceInFileSync(remoteMedatadataHistoryNew, '-TST.', '-tst.');
            tools.replaceInFileSync(remoteMedatadataHistoryNew, '-INT.', '-int.');
            tools.replaceInFileSync(remoteMedatadataHistoryNew, '-ACC.', '-acc.');
            tools.replaceInFileSync(remoteMedatadataHistoryNew, '-DLT.', '-dlt.');
            tools.replaceInFileSync(remoteMedatadataHistoryNew, '-TRN.', '-trn.');
            tools.replaceInFileSync(remoteMedatadataHistoryNew, '-PPD.', '-ppd.');
        }

        if (tools.isFileExists(remoteMedatadataEnvsNew)) {
            tools.replaceInFileSync(remoteMedatadataEnvsNew, '"DEV"', '"dev"');
            tools.replaceInFileSync(remoteMedatadataEnvsNew, '"TST"', '"tst"');
            tools.replaceInFileSync(remoteMedatadataEnvsNew, '"INT"', '"int"');
            tools.replaceInFileSync(remoteMedatadataEnvsNew, '"ACC"', '"acc"');
            tools.replaceInFileSync(remoteMedatadataEnvsNew, '"DLT"', '"dlt"');
            tools.replaceInFileSync(remoteMedatadataEnvsNew, '"TRN"', '"trn"');
            tools.replaceInFileSync(remoteMedatadataEnvsNew, '"PPD"', '"ppd"');
            tools.replaceInFileSync(remoteMedatadataEnvsNew, '"PROD"', '"prd"');

            tools.replaceInFileSync(remoteMedatadataEnvsNew, '-TST.', '-tst.');
            tools.replaceInFileSync(remoteMedatadataEnvsNew, '-INT.', '-int.');
            tools.replaceInFileSync(remoteMedatadataEnvsNew, '-ACC.', '-acc.');
            tools.replaceInFileSync(remoteMedatadataEnvsNew, '-DLT.', '-dlt.');
            tools.replaceInFileSync(remoteMedatadataEnvsNew, '-TRN.', '-trn.');
            tools.replaceInFileSync(remoteMedatadataEnvsNew, '-PPD.', '-ppd.');
        }
    })
    .catch((e) => {
        console.log(e);
    })    
}