/**
Copyright: 2024 Contrast Security, Inc
  Contact: support@contrastsecurity.com
  License: Commercial

  NOTICE: This Software and the patented inventions embodied within may only be
  used as part of Contrast Security’s commercial offerings. Even though it is
  made available through public repositories, use of this Software is subject to
  the applicable End User Licensing Agreement found at
  https://www.contrastsecurity.com/enduser-terms-0317a or as otherwise agreed
  between Contrast Security and the End User. The Software may not be reverse
  engineered, modified, repackaged, sold, redistributed or otherwise used in a
  way not consistent with the End User License Agreement.
*/
'use strict';
const LibraryManifest = require('./library-manifest');
const logger = require('../../../core/logger')('contrast:libraries');
const fs = require('fs');
const pathModule = require('path');

module.exports = class Library {
  /**
   * @param {Object} data              - Node in the dependency tree returned by read-installed
   * @param {string} name
   * @param {string} version
   * @param {string} data.path         - Path to the dependency on filesystem
   * @param {Object} data.parent       - Module for which this module is a subdependencies
   * @param {Object} data.dependencies - Subdependencies of this module
   * @param {*} data.*                 - package.json data for the module
   */
  constructor(data, tags) {
    this._name = data.name;
    this._path = data.path;
    this.version = data.version;
    this._id = `${this._name}:${this.version}`;
    this.hash = Library.getHash(data);
    this.file = `${this._name}-${this.version}`;
    this.url = data.homepage;
    this.manifest = new LibraryManifest(data);
    this.tags = tags;
    this.fileCount = data.fileCount || 0;
    this.loc = data.loc || 0;
  }

  /**
   * Returns serialized version of library
   */
  toSerializable() {
    return {
      version: this.version,
      hash: this.hash,
      file: this.file,
      url: this.url,
      manifest: this.manifest.toSerializable(),
      usedClassCount: 0,
      classCount: this.fileCount,
      tags: this.tags,
    };
  }

  /**
   * Creates hash from package metadata
   * @param {Object} data metadata from package.json
   */
  static getHash(data) {
    let shasum;
    if (data._shasum) {
      shasum = data._shasum;
    } else if (data.dist) {
      ({ shasum } = data.dist);
    } else {
      const { name, version } = data;
      shasum = `${name}:${name}:${version}`;
    }

    return shasum;
  }

  /**
   * Valid file extensions for a library composition data
   *
   * @param {string} file path to module
   */
  static applicableFile(file) {
    return (
      ['.js', '.node', '.cjs', '.mjs'].filter((validExtension) =>
        file.endsWith(validExtension)
      ).length > 0
    );
  }

  readdir(path, callback) {
    if (!callback) {
      return new Promise((resolve, reject) => {
        this.readdir(path, (err, data) => {
          if (err) {
            reject(err);
          } else {
            resolve(data);
          }
        });
      });
    }

    let list = [];

    fs.readdir(path, (err, files) => {
      if (err) {
        return callback(err);
      }

      let pending = files.length;
      if (!pending) {
        return callback(null, list);
      }

      files.forEach((file) => {
        const filePath = pathModule.join(path, file);
        fs.stat(filePath, (_err, stats) => {
          if (_err) {
            return callback(_err);
          }

          if (stats.isDirectory() && !filePath.endsWith('/node_modules')) {
            this.readdir(filePath, (__err, res) => {
              if (__err) {
                return callback(__err);
              }

              list = list.concat(res);
              pending -= 1;
              if (!pending) {
                return callback(null, list);
              }
            });
          } else {
            list.push(filePath);
            pending -= 1;
            if (!pending) {
              return callback(null, list);
            }
          }
        });
      });
    });
  }

  /**
   * Counts all the valid files in a module directory
   */
  getComposition() {
    // ignore nested node_modules
    return this.readdir(this._path)
      .then((files) => {
        this.fileCount = files.filter((file) =>
          Library.applicableFile(file)
        ).length;
      })
      .catch((err) => {
        logger.error(
          `unable to get module composition for ${this._name} ${this.version}.  Set agent.node.app_root to location of installed node_modules`
        );
      });
  }
};
