"use strict";

function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

var NodeGit = require("../");

var LookupWrapper = NodeGit.Utils.lookupWrapper;
var Tag = NodeGit.Tag;
var signatureRegexesBySignatureType = {
  gpgsig: [/-----BEGIN PGP SIGNATURE-----[\s\S]+?-----END PGP SIGNATURE-----/gm, /-----BEGIN PGP MESSAGE-----[\s\S]+?-----END PGP MESSAGE-----/gm],
  x509: [/-----BEGIN SIGNED MESSAGE-----[\s\S]+?-----END SIGNED MESSAGE-----/gm]
};
/**
 * Retrieves the tag pointed to by the oid
 * @async
 * @param {Repository} repo The repo that the tag lives in
 * @param {String|Oid|Tag} id The tag to lookup
 * @return {Tag}
 */

Tag.lookup = LookupWrapper(Tag);
/**
 * @async
 * @param {Repository} repo
 * @param {String} tagName
 * @param {Oid} target
 * @param {Signature} tagger
 * @return {String}
 */

Tag.createBuffer = function (repo, tagName, target, tagger, message) {
  return NodeGit.Object.lookup(repo, target, NodeGit.Object.TYPE.ANY).then(function (object) {
    if (!NodeGit.Object.typeisloose(object.type())) {
      throw new Error("Object must be a loose type");
    }

    var id = object.id().toString();
    var objectType = NodeGit.Object.type2String(object.type());
    var lines = ["object ".concat(id), "type ".concat(objectType), "tag ".concat(tagName), "tagger ".concat(tagger.toString(true), "\n"), "".concat(message).concat(message.endsWith("\n") ? "" : "\n")];
    return lines.join("\n");
  });
};
/**
 * @async
 * @param {Repository} repo
 * @param {String} tagName
 * @param {Oid} target
 * @param {Signature} tagger
 * @param {String} message
 * @param {Number} force
 * @param {Function} signingCallback Takes a string and returns a string
 *                                   representing the signed message
 * @return {Oid}
 */


Tag.createWithSignature = function (repo, tagName, target, tagger, message, force, signingCallback) {
  var tagBuffer;
  return Tag.createBuffer(repo, tagName, target, tagger, message).then(function (tagBufferResult) {
    tagBuffer = tagBufferResult;
    return signingCallback(tagBuffer);
  }).then(function (_ref) {
    var code = _ref.code,
        signedData = _ref.signedData;

    switch (code) {
      case NodeGit.Error.CODE.OK:
        {
          var normalizedEnding = signedData.endsWith("\n") ? "" : "\n";
          var signedTagString = tagBuffer + signedData + normalizedEnding;
          return Tag.createFromBuffer(repo, signedTagString, force);
        }

      case NodeGit.Error.CODE.PASSTHROUGH:
        return Tag.create(repo, tagName, target, tagger, message, force);

      default:
        {
          var error = new Error("Tag.createWithSignature threw with error code ".concat(code));
          error.errno = code;
          throw error;
        }
    }
  });
};
/**
 * Retrieves the signature of an annotated tag
 * @async
 * @param {String} signatureType
 * @return {String|null}
 */


Tag.prototype.extractSignature = function () {
  var signatureType = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "gpgsig";
  var id = this.id();
  var repo = this.repo;
  var signatureRegexes = signatureRegexesBySignatureType[signatureType];

  if (!signatureRegexes) {
    throw new Error("Unsupported signature type");
  }

  return repo.odb().then(function (odb) {
    return odb.read(id);
  }).then(function (odbObject) {
    var odbData = odbObject.toString();

    var _iterator = _createForOfIteratorHelper(signatureRegexes),
        _step;

    try {
      for (_iterator.s(); !(_step = _iterator.n()).done;) {
        var regex = _step.value;
        var matchResult = odbData.match(regex);

        if (matchResult !== null) {
          return matchResult[0];
        }
      }
    } catch (err) {
      _iterator.e(err);
    } finally {
      _iterator.f();
    }

    throw new Error("this tag is not signed");
  });
};