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


// ONE-TIME ONLY !!!! as manual updates has been made...


const defaultSample =         {
  "path": "sample -- full options",
  "authMetadata": {
      "id": "SECUNDA_TASK_ID",
      "ids": "['SECUNDA_TASK_ID', 'SECUNDA_TASK_ID', ...]",
      "canActivate": "[AuthGuardService] -- if data.id or data.ids present"
  },
  "lazyLoadDef": {
      "npmPkg": "@scope/packageName",
      "moduleName": "RootPackageModuleName"
  },
  "remoteDef": {
      "featureName": "FEATURE_FLAG_NAME in openid config files - to activate/deactivate links in environment (runtime config)",
      "moduleId": "used by the elementLoader - name of the remote name in the config : scope-package-euiXX-remote-el-ui",
      "elementTag": "used by the elementLoader - unique name identifying the remote - scope-package-vXX",
      "iframe": true
  },
  "menuLinkDef": {
      "label": "sidebar-link.KEY - as defined in the assets/i18n/lng files",
      "iconClass": "eui-icon eui-icon-ICON_NAME for the menu link entry in the sidebar",
      "deniedRightId": "SECUNDA_TASK_ID - denied right to not show this link for category of user having this taskId set",
      "allowedRightId": "SECUNDA_TASK_ID - allowed right to show this link for category of user having this taskId set",
      "allowedRightIds": "['SECUNDA_TASK_ID', 'SECUNDA_TASK_ID', ...] - multiple taskId are allowed to view this link",
      "parenLinkId": "PARENT_ID -- children of existing parent in defs-links.json menu links structure"
  }
};


Promise.resolve()
  .then(() => {
    const rPath = path.join(process.cwd(), 'packages', 'mywp-routes-config', 'assets', 'route-defs.dev.json');
    const rDev = tools.getJsonFileContent(rPath);
    const lPath = path.join(process.cwd(), 'packages', 'mywp-routes-config', 'assets', 'route-defs-links.json');
    const rLink = tools.getJsonFileContent(lPath);
    const plPath = path.join(process.cwd(), 'packages', 'mywp-routes-config', 'assets', 'route-defs-base-v10-playground.json');
    const rPg = tools.getJsonFileContent(plPath);
    const plPath15 = path.join(process.cwd(), 'packages', 'mywp-routes-config', 'assets', 'route-defs-base-v15-playground.json');
    const rPg15 = tools.getJsonFileContent(plPath15);

    const parentLinks = rLink.filter(r => r.parentId !== undefined);

    // base routes

    const resultRoutes = [];

    resultRoutes.push(defaultSample);

    rDev.forEach((route) => {
      const n = {};
      n.path = route.path;

      const auth = {};
      let lazy = {};
      let remote = {};

      lazy.npmPkg = 'TO_BE_FILLED';
      lazy.moduleName = 'TO_BE_FILLED';

      if (route.data) {
        if (route.data.id) {
          auth.id = route.data.id;
          auth.canActivate = "[AuthGuardService]";
          n.authMetadata = auth;
        }
        if (route.data.ids) {
          auth.ids = route.data.ids;
          auth.canActivate = "[AuthGuardService]";
          n.authMetadata = auth;
        }

        if (route.data.elementTag) {
          remote = {
            featureName: route.data.featureName,
            moduleId: route.data.moduleId,
            elementTag: route.data.elementTag,
            iframe: route.data.iframe,
          }
          if (route.data.moduleIdNew) {
            remote.moduleIdNew = route.data.moduleIdNew;
          }
        }
      }

      const linkRoute = rLink.filter((r) => {
        if (r.url) {
          return r.url.indexOf(route.path) > 0;
        }
      })[0];

      if (linkRoute) {
        n.menuLinkDef = linkRoute;

      } else {
        let childRoute;

        parentLinks.forEach((pl) => {
          pl.children.forEach((r) => {
            if (r.url) {
              if (r.url.indexOf(route.path) > 0) {
                childRoute = r;
                childRoute.parentLinkId = pl.parentId;
              }
            }
          });

          if (childRoute) {
            n.menuLinkDef = childRoute;
          }
        })
      }

      let mod, imp;
      let mdRoute;

      mdRoute = rPg.filter(r => r.path === route.path || r.path === route.path.substr(0, route.path.length - 4))[0];

      if (mdRoute) {
        const libModFilename = mdRoute.loadChildren.substr(0, mdRoute.loadChildren.length - 7);
        const libModFilePath = path.join(process.cwd(), 'packages', 'mywp-host-ui', 'assets', '10.x', 'app-sources-playground', 'app', libModFilename + '.ts');

        if (tools.isFileExists(libModFilePath)) {
          const libModFileContent = tools.getFileContent(libModFilePath);
          const lines = libModFileContent.split('\n');
          let libModLine;
          libModLine = lines.filter(l => l.indexOf('LibModule') > 0)[0];
          if (!libModLine) {
            libModLine = lines[1];
          }
          // console.log(libModFilename, libModLine);
          const words = libModLine.split(' ');
          // console.log(words);
          mod = words.filter(w => w.indexOf('Module') > -1)[0];
          // console.log(route.path, mod);
          const impLast = words[words.length-1];
          imp = impLast.substr(1, impLast.length - 4);
        }
      }

      mdRoute = rPg15.filter(r => r.path === route.path || r.path === route.path.substr(0, route.path.length - 4))[0];

      if (mdRoute) {
        const libModFilename = mdRoute.loadChildren.substr(0, mdRoute.loadChildren.length - 7);
        const libModFilePath = path.join(process.cwd(), 'packages', 'mywp-host-ui', 'assets', '15.x', 'app-sources-playground', 'app', libModFilename + '.ts');

        if (tools.isFileExists(libModFilePath)) {
          const libModFileContent = tools.getFileContent(libModFilePath);
          const lines = libModFileContent.split('\n');
          let libModLine;
          libModLine = lines.filter(l => l.indexOf('LibModule') > 0)[0];
          if (!libModLine) {
            libModLine = lines[1];
          }
          // console.log(libModFilename, libModLine);
          const words = libModLine.split(' ');
          // console.log(words);
          mod = words.filter(w => w.indexOf('Module') > -1)[0];
          // console.log(route.path, mod);
          const impLast = words[words.length-1];
          imp = impLast.substr(1, impLast.length - 4);
        }
      }

      if (route.path.indexOf('delegations-manager-v15') > -1) {
        mod = 'DelegationManagerModule';
        imp = '@mywp/delegations-manager';
      }
      if (route.path.indexOf('task-details-v15') > -1) {
        mod = 'CcTaskDetailsModule';
        imp = '@cc/task-details';
      }
      if (route.path.indexOf('item-v15') > -1) {
        mod = 'CcPortfolioItemModule';
        imp = '@cc/portfolio-item';
      }
      if (route.path.indexOf('process-v15') > -1) {
        mod = 'ProcessCentreListModule';
        imp = '@cc/process-centre';
      }
      if (route.path.indexOf('flex-v15') > -1) {
        mod = 'FlexModule';
        imp = '@cc/flex';
      }
      if (route.path.indexOf('rsp-management') > -1) {
        mod = 'Module';
        imp = '@rsp/management';
      }
      if (route.path.indexOf('cps-tools') > -1) {
        mod = 'CpsCigipModule';
        imp = '@cps/cigip-orchestrator';
      }
      if (route.path.indexOf('decide-poc') > -1) {
        mod = 'DecideSectionModule';
        imp = '@cc/decidepoc/section';
      }


      if (mod) {
        lazy.moduleName = mod;
      } else {
        console.log('mod not found : ', route.path);
      }
      if (imp) {
        lazy.npmPkg = imp;
      } else {
        console.log('import not found : ', route.path);
      }

      n.lazyLoadDef = lazy;
      n.remoteDef = remote;

      resultRoutes.push(n);
    });

    resultRoutes.push({
        "path": "notifications",
        "menuLinkDef": {
            "url": "/notifications/view-all",
            "label": "sidebar-link.NOTIFICATIONS",
            "iconClass": "ux-icon ux-icon-envelope-o",
            "deniedRightId": "IGNORE_NOTIFICATION"
        },
        "lazyLoadDef": {
            "npmPkg": "@mywp/notifications",
            "moduleName": "NotificationsModule"
        }
    });

    tools.writeJsonFileSync(path.join(process.cwd(), 'packages', 'mywp-host-ui', 'assets', 'routes', 'route-defs-base.json'), resultRoutes);
    // console.log(JSON.stringify(resultRoutes, null, 2));


    // env routes
    const envs = ['dev', 'test', 'int', 'acc', 'dlt', 'trn', 'prod'];

    envs.forEach((env) => {
      const envPath = path.join(process.cwd(), 'packages', 'mywp-routes-config', 'assets', `route-defs.${env}.json`);
      const rEnv = tools.getJsonFileContent(envPath);

      const routes = rEnv.map((r) => {
        return {
          "path": r.path,
          "remote": true
        };
      });

      routes.push({
        path: "notifications",
        lazy: true
      });

      tools.writeJsonFileSync(path.join(process.cwd(), 'packages', 'mywp-host-ui', 'assets', 'routes', `route-defs.${env}.json`), routes);
    });


    // playground routes
    const pgs = ['v10', 'v15'];

    pgs.forEach((pg) => {
      const pgPath = path.join(process.cwd(), 'packages', 'mywp-routes-config', 'assets', `route-defs-base-${pg}-playground.json`);
      const rPg = tools.getJsonFileContent(pgPath);

      const routes = rPg.map((r) => {
        return {
          "path": r.path,
          "lazy": true
        };
      });

      routes.push({
        path: "notifications",
        lazy: true
      });

      tools.writeJsonFileSync(path.join(process.cwd(), 'packages', 'mywp-host-ui', 'assets', 'routes', `route-defs-base-${pg}-playground.json`), routes);
    });
  })
