'use strict';

const path = require('path');

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

const injectionUtils = require('./injection/injection-utils');
const translationUtils = require('./translations/translation-utils');
const routesReplacement = require('./routes-replacement/routes-replacement');

const configUtils = require('../../csdr/config/config-utils');
const svgUtils = require('../svg-utils');

let { dryRun } = tools.getArgs();

module.exports.preBuild = (project, envTarget, build, configEnvTarget) => {

  return Promise.resolve()

    .then(() => {
      tools.logTitle('PRE-BUILD : preparing the project...');
    })

    // inject external app sources declaration
    .then(() => {
      if (project.externalSources) {
        return injectionUtils.externals.injectExternalAppSources(project, build);
      }
    })

    .then(() => {
      return configUtils.angular.registerAngularProjectDef(project, build);
    })


    // inject project config if set as external config deps
    .then(() => {
      if (project.config) {
        return injectionUtils.config.injectConfig(project);
      }
    })

    // generate compiled translation files
    .then(() => {
      if (project.build && project.build.compiledTranslations) {
        const scopes = project.build.translationScopes;
        if (scopes) {
          return translationUtils.projects.generate(scopes, project);
        } else {
          return translationUtils.projects.generate(null, project);
        }
      }
    })

    // inject external features declaration
    .then(() => {
      if (project.features && project.features.external) {
        return injectionUtils.externals.injectExternalFeatures(project);
      }
    })

    // inject skeleton sources
    .then(() => {
      if (project.csdrSkeleton) {
        return injectionUtils.skeletons.injectCsdrSkeletonSources(project);

      } else if (project.csdrSkeletonEuiShowcase) {
        return injectionUtils.skeletons.injectCsdrSkeletonEuiShowcaseSources(project);

      } else if (project.csdrFullSkeleton) {
        if (project.build && project.build.euiVersion === '13.x') {
          return injectionUtils.skeletons.injectCsdrFullSkeletonSources(project, '13.x');
        } else if (project.build && project.build.euiVersion === '14.x') {
          return injectionUtils.skeletons.injectCsdrFullSkeletonSources(project, '14.x');
        } else if (project.build && project.build.euiVersion === '15.x') {
          return injectionUtils.skeletons.injectCsdrFullSkeletonSources(project, '15.x');
        } else if (project.build && project.build.euiVersion === '16.x') {
          return injectionUtils.skeletons.injectCsdrFullSkeletonSources(project, '16.x');
        } else if (project.build && project.build.euiVersion === '17.x') {
          return injectionUtils.skeletons.injectCsdrFullSkeletonSources(project, '17.x');
        } else if (project.build && project.build.euiVersion === '18.x') {
          return injectionUtils.skeletons.injectCsdrFullSkeletonSources(project, '18.x');
        } else if (project.build && project.build.euiVersion === '19.x') {
          return injectionUtils.skeletons.injectCsdrFullSkeletonSources(project, '19.x');
        } else {
          return injectionUtils.skeletons.injectCsdrFullSkeletonSources(project);
        }
      }
    })

    // openId files replacement and app config injection
    .then(() => {
      return injectionUtils.openid.injectConfig(project, configEnvTarget);
    })

    // replace app routes
    .then(() => {
      if (project.config && project.externalRoutesSources) {
        return routesReplacement.buildRoutes(project, envTarget, build);
      }
    })
    // generate remotes metadata during CI build of the host only (feeding the about page)
    .then(() => {
      if (project.config && project.externalRoutesSources && build) {
        return routesReplacement.extractRemotesMetadata(project, configEnvTarget);
      }
    })

    // processing custom script injection if enabled in project config
    .then(() => {
      return this.processCustomEnvScriptInjection(project, envTarget, configEnvTarget);
    })

    // checking if project as own pre-build.js script defined, and executing it
    .then(() => {
      const prebuildScript = path.join(project.paths.rootPath, 'pre-build.js');

      if (!dryRun && tools.isFileExists(prebuildScript)) {
        tools.logInfo('Executing pre-build script');

        return tools.runScript(`node ${prebuildScript}`);
      } else {
        tools.logInfo('DRY-RUN or pre-build script not found in project folder --- skipping');
      }
    })

    .catch((e) => {
      throw e;
    })
};


module.exports.processCustomEnvScriptInjection = (project, envTarget, configEnvTarget) => {
  return Promise.resolve()
    .then(() => {
      if (project.build && project.build.customEnvScriptInjection) {
        let envTargetGen;

        if (project.build && project.build.customEnvScriptInjectionConfigEnvTarget) {
          envTargetGen = configEnvTarget;
          tools.logInfo(`Processing custom script injection for ${project.name} - configEnvTarget: ${envTargetGen}`);
        } else {
          envTargetGen = envTarget;
          tools.logInfo(`Processing custom script injection for ${project.name} - envTarget: ${envTargetGen}`);
        }

        const scriptName = project.build.customEnvScriptInjection[envTargetGen.toLowerCase()];
        if (!scriptName) {
          tools.logWarning('Unable to find script replacement definition for envTarget/configEnvTarget...skipping');
          return;
        } else {
          tools.logInfo(`Script to replace : ${scriptName}`);
          const injectedScript = `<script type="text/javascript" src="${scriptName}" crossorigin="anonymous"></script>`;
          const placeholderToReplace = '<!-- CUSTOM SCRIPT INJECTION PLACEHOLDER -->';
          const fileToReplace = path.join(project.paths.angularPath, 'src', 'index.html');

          if (tools.isFileExists(fileToReplace)) {
            return tools.replaceInFile(fileToReplace, placeholderToReplace, injectedScript);
          } else {
            tools.logWarning(`Source replacement file does not exist : ${fileToReplace}`);
          }
        }
      }
    })

    .catch((e) => {
      throw e;
    });
};

module.exports.processSvgAssets = (project) => {
  return Promise.resolve()
    .then(() => {
      const svgsInPath = path.join(project.paths.rootPath, 'src', 'assets', 'svg');
      const svgsSpritePath = path.join(svgsInPath, sprites);
      const svgsSpriteFile = 'sprite.svg';

      return svgUtils.generateSvgsSprite(svgsInPath, svgsSpritePath, svgsSpriteFile);
    })

    .catch((e) => {
      throw e;
    });
};
