/**
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 { dtm } = require('@contrast/protobuf-api');
const { RoutesList } = require('./route-coverage');

module.exports = function ApplicationUpdate(data) {
  if (data.toSerializable) {
    data = data.toSerializable();
  }

  const { libraries, coverage, routes } = data;
  return new dtm.ApplicationUpdate({
    1: coverage, //                         2 coverage_loc
    7: translateLibs(libraries), //         8 libraries
    8: routes ? RoutesList(routes) : [] //   9 routes
  });
};

function translateLibs(libraries) {
  if (!libraries) return libraries;
  const serializedLibs = [];
  for (const lib of libraries) {
    // protobuf map for key: {a: b, c: d} looks like
    // [key [b, d]].
    const entry = [];
    const tags = lib.tags || [];

    entry.push(lib.hash);
    entry.push(
      new dtm.Library({
        0: lib.hash, //                               1        hash_code
        1: lib.file, //                               2        file_path
        2: lib.url, //                                3              url
        3: lib.version, //                            4          version
        4: 0, //                                      5             tloc
        5: lib.classCount, //                         6      class_count
        6: lib.usedClassCount, //                     7 used_class_count
        9: lib.manifest, //                          10         manifest
        10: tags.join(',') //                        11             tags
      }).array
    );

    serializedLibs.push(entry);
  }

  return serializedLibs;
}
