"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var _path = _interopRequireDefault(require("path"));

var _request = _interopRequireDefault(require("./request"));

var _libraryImpactConfig = _interopRequireDefault(require("./libraryImpactConfig"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

let dependencies = ['@zohodesk/components', '@zohodesk/dot', '@zohodesk/icons', '@zohodesk/svg', '@zohodesk/variables'];

let getCurrentDependenciesInfo = () => {
  let packageJson = require(_path.default.join(process.cwd(), 'package.json'));

  let info = {};

  for (let dependency of dependencies) {
    info[dependency] = packageJson.dependencies[dependency];
  }

  return info;
};

let getLiveDependenciesInfo = (branch, tokenGit) => new Promise((resolve, reject) => {
  let url = `${'ht'}${'tps'}://zgit.csez.zohocorpin.com/api/v4/projects/1143/repository/files/jsapps%2Fsupportapp%2Fpackage.json?ref=${branch}`;
  (0, _request.default)({
    url,
    headers: {
      'PRIVATE-TOKEN': tokenGit
    }
  }).then(res => {
    let {
      content
    } = JSON.parse(res.body);
    let {
      dependencies: depend
    } = JSON.parse(Buffer.from(content, 'base64').toString());
    let info = {};

    for (let dependency of dependencies) {
      info[dependency] = depend[dependency];
    }

    resolve(info);
  }).catch(reject);
});

let getDependencyChangeset = (dependency, version) => {
  return new Promise(resolve => {
    let url = `${'ht'}${'tp'}://tsi-desk-mock.tsi.zohocorpin.com:8080/Hbase/getKey?method=getkey&tablename=${dependency}_changesets&row=dependencies_changesets&column=${version}`;
    (0, _request.default)({
      url
    }).then(({
      body
    }) => {
      if (body == "") {
        console.log("Changeset for the " + dependency + " version " + version + " not stored in Hbase!");
      }

      resolve(body);
    });
  });
};

let getImpactDiff = (srcBranch, targetBranch, appName) => new Promise(resolve => {
  let diff = {
    [appName]: {}
  };
  let domain = _libraryImpactConfig.default[appName].impactDomain;
  let serviceName = _libraryImpactConfig.default[appName].impactService;
  (0, _request.default)({
    url: `${domain}/impact/ImpactModuleAction.do?action=getCommitDiffFileDetail&serviceName=${serviceName}&masterBranchCommitHash=${targetBranch}&buildCommitHash=${srcBranch}`
  }).then(res => {
    let {
      body
    } = res;
    let {
      DIFF_FILES
    } = JSON.parse(body);
    Object.keys(DIFF_FILES).forEach(key => {
      DIFF_FILES[key].forEach(({
        FILEPATH
      }) => {
        if (FILEPATH.includes(`jsapps/${appName === 'AppSource' ? 'supportapp/src' : appName}`) && FILEPATH.endsWith('.js') && !FILEPATH.includes('.spec')) {
          let {
            name,
            ext
          } = _path.default.parse(FILEPATH);

          if (!diff[appName][key]) {
            diff[appName][key] = [];
          }

          diff[appName][key].push({
            name: name + ext,
            FILEPATH
          });
        }
      });
    });
    resolve(diff);
  });
});

var _default = (srcBranch, liveBranch, tokenGit, serviceName = 'ZohoDeskLibrary') => new Promise(resolve => {
  let currentDependencies = getCurrentDependenciesInfo();
  getLiveDependenciesInfo(liveBranch, tokenGit).then(liveDependencies => {
    let diff = {};
    let promises = [];

    for (let dependency of dependencies) {
      promises.push(new Promise(resolve => {
        if (currentDependencies[dependency] !== liveDependencies[dependency]) {
          let sanitizedName = dependency.replace('@', '').replace(/\//g, '_');
          let [, folderName] = sanitizedName.split('_');
          diff[folderName] = {};
          let p1 = getDependencyChangeset(sanitizedName, currentDependencies[dependency]);
          let p2 = getDependencyChangeset(sanitizedName, liveDependencies[dependency]);
          Promise.all([p1, p2]).then(([currentChangeset, liveChangeset]) => {
            getImpactDiff(liveChangeset, currentChangeset, folderName).then(impacts => {
              Object.assign(diff, impacts);
              resolve();
            });
          });
        } else {
          resolve();
        }
      }));
    }

    promises.push(new Promise(resolve => {
      getImpactDiff(srcBranch, liveBranch, 'AppSource').then(impacts => {
        Object.assign(diff, impacts);
        resolve();
      });
    }));
    Promise.all(promises).then(() => {
      resolve(diff);
    });
  }).catch(e => {
    throw e;
  });
});

exports.default = _default;