"use strict";

var _namespace = _interopRequireDefault(require("../utils/namespace"));

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

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 $ = require('jquery');

require('../../../lib/jquery-xpath/jquery.xpath');

var meiprocessing = {};

meiprocessing.getClosestMeter = function () {
  var XPevent = this;
  var XPscoreDef = XPevent.xpath("preceding::mei:scoreDef[1]", _namespace["default"]); // Process for beat data if the scoreDef defines meter, otherwise lookback

  var count = XPscoreDef.attr("meter.count");
  var unit = XPscoreDef.attr("meter.unit");

  if (!count || !unit) {
    var count_elm = XPscoreDef.xpath("descendant::mei:meterSig", _namespace["default"]);

    if (count_elm.length > 0) {
      // Remove throw error.
      // if (count_elm.length > 1) {
      //    throw "Mixed meter is not supported";
      // }
      var _count = count_elm[0].xpath("@count").val();

      var _unit = count_elm[0].xpath("@unit").val();

      if (!_count || !_unit) {
        throw "Could not locate meter and compute beats";
      }
    } // No meter specified, lookback
    else {
      return meiprocessing.getClosestMeter.apply(XPscoreDef);
    }
  }

  return {
    "count": count,
    "unit": unit
  };
};

meiprocessing.getDurationToMeter = function () {
  var XPevent = this;

  if (XPevent.xpath("self::mei:mRest", _namespace["default"]).length > 0) {
    return "all";
  } else {
    var dur = XPevent.xpath("@dur").val();

    if (!dur) {
      throw "Element has no duration.";
    }

    var dots = 0;

    if (dur == "breve") {
      dur = 0.5;
    } else if (dur == "long") {
      dur = 0.25;
    }

    dur = Number(dur);
    var attr = XPevent.xpath("@dots").val();
    var els = XPevent.xpath("dot");

    if (attr) {
      dots = parseInt(attr);
    } else if (els) {
      dots = els.length;
    } // Calculate duration relative to meter


    var meter = meiprocessing.getClosestMeter.apply(this);
    var relative_dur = meter.unit / dur;
    var dot_dur = dur;

    for (var _i = 0, _Array$from = Array.from(new Array(dots), function (x, i) {
      return i;
    }); _i < _Array$from.length; _i++) {
      var d = _Array$from[_i];
      dot_dur = dot_dur * 2;
      relative_dur += meter.unit / dot_dur;
    } // Adjust duration if this event is contained in a tuplet
    // TODO: deal with teupletspan


    var XPtupl = XPevent.xpath("ancestor::mei:tuplet", _namespace["default"]);

    if (XPtupl.length > 0) {
      var numbase = XPtupl.xpath("@numbase");
      var num = XPtupl.xpath("@num");

      if (!num || !numbase) {
        throw "Cannot understand tuplet beat: both @num and @numbase must be present";
      } else {
        var tupl_ratio = parseFloat(numbase.val()) / parseFloat(num.val());
        relative_dur = relative_dur * tupl_ratio;
      }
    }

    return relative_dur;
  }
};

meiprocessing.getEventBeat = function () {
  var XPevent = this;

  if (XPevent.xpath("self::mei:mRest", _namespace["default"]).length > 0) {
    return "all";
  } else {
    var dur = XPevent.xpath("@dur").val();

    if (!dur) {
      throw "Element has no duration.";
    }

    var beat = 1.0; // This is a bit inefficient because xpath.js doesn't support generate-id().

    var XPstaff = XPevent.xpath("ancestor::mei:staff[1]", _namespace["default"]);

    var _iterator = _createForOfIteratorHelper(XPstaff.xpath("descendant::*[@dur][not(@grace)]")),
        _step;

    try {
      for (_iterator.s(); !(_step = _iterator.n()).done;) {
        var el = _step.value;
        var $el = $(el);

        if ($el.attr("xml:id") == XPevent.attr("xml:id")) {
          break;
        }

        beat += meiprocessing.getDurationToMeter.apply($el);
      }
    } catch (err) {
      _iterator.e(err);
    } finally {
      _iterator.f();
    }

    return parseFloat(beat.toFixed(4));
  }
};

$.extend($.prototype, meiprocessing);