"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

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

var _jquery = _interopRequireDefault(require("jquery"));

var Backbone = _interopRequireWildcard(require("backbone"));

var _verovioInteractionView = _interopRequireDefault(require("./views/verovioInteractionView"));

var _highlightView = _interopRequireDefault(require("./views/highlightView"));

var _modelMEIdata = _interopRequireDefault(require("./data/model-MEIdata"));

var _backboneEvents = _interopRequireDefault(require("./utils/backbone-events"));

var _verovioExt = _interopRequireDefault(require("./utils/verovio-ext"));

var _EMAexpr = _interopRequireDefault(require("./components/EMAexpr"));

var _pagination = _interopRequireDefault(require("./components/pagination"));

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

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

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; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

var Continuo = /*#__PURE__*/function (_Backbone$View) {
  _inherits(Continuo, _Backbone$View);

  var _super = _createSuper(Continuo);

  function Continuo() {
    _classCallCheck(this, Continuo);

    return _super.apply(this, arguments);
  }

  _createClass(Continuo, [{
    key: "initialize",
    value: function initialize(options) {
      var _this = this;

      this.mei = options.mei;
      this.meiString = options.meiString;
      this.omas = options.omas;
      this.verovioToolkit = options.verovioToolkit;
      this.verovioOptions = options.verovioOptions;
      this.paginate = options.paginate;
      this.showPageCtrls = options.showPageCtrls === null || options.showPageCtrls === undefined ? true : options.showPageCtrls;
      this.page = 1;
      this.selectedElements = [];
      this.highlightedElements = [];
      this.listenTo(_backboneEvents["default"], 'addFile', this.addFile);
      this.listenTo(_backboneEvents["default"], 'component:pagination:next', function () {
        _this.renderPage(_this.page + 1);
      });
      this.listenTo(_backboneEvents["default"], 'component:pagination:prev', function () {
        _this.renderPage(_this.page - 1);
      });
    }
  }, {
    key: "addFile",
    value: function addFile(textData) {
      var _this2 = this;

      // Create score
      var container = this.$el.find(".cnt-container");
      this.EMAComponent.trigger('component:emaBox:url', textData["url"]);
      var doc = new DOMParser().parseFromString(textData["string"], 'text/xml');
      this.MEIdata = new _modelMEIdata["default"]({
        "doc": doc,
        "string": textData["string"]
      });
      this.MEIdata.generate_ids(); // Sadly, importing Verovio crashes babelify,
      // so we assume it's globally available
      // i.e. verovio must be defined.

      var vrvToolkit = this.verovioToolkit ? this.verovioToolkit : new verovio.toolkit();
      this.vrvToolkit = vrvToolkit;
      var scale = 50;
      var options = this.verovioOptions ? this.verovioOptions : {
        pageWidth: this.$el.width() * 100 / scale,
        pageHeight: this.$el.height() * 100 / scale,
        ignoreLayout: 1,
        adjustPageHeight: 1,
        border: 50,
        scale: scale
      };
      vrvToolkit.setOptions(options);
      var mei = textData["string"];
      vrvToolkit.loadData(mei + "\n", "");

      if (this.paginate) {
        this.page = 1;
        var svg = vrvToolkit.renderPage(1);
        var ext_svg = (0, _verovioExt["default"])(svg);
        container.append(ext_svg);
      } else {
        var pgs = vrvToolkit.getPageCount();

        for (var _i = 0, _Array$from = Array.from(new Array(pgs), function (x, i) {
          return i;
        }); _i < _Array$from.length; _i++) {
          var page = _Array$from[_i];

          var _svg = vrvToolkit.renderPage(page + 1);

          var _ext_svg = (0, _verovioExt["default"])(_svg);

          container.append(_ext_svg);
        }
      }

      this.interView = new _verovioInteractionView["default"]({
        "el": container,
        "model": this.MEIdata
      });
      this.interView.on("component:emaBox", function (expr) {
        return _this2.EMAComponent.trigger("component:emaBox", expr);
      });
      this.interView.on('selectElement', function (id) {
        _this2.selectedElements.push(id);

        _this2.trigger("selected", id);
      });
      this.interView.on('deselectElement', function (id) {
        var index = _this2.selectedElements.indexOf(id);

        if (index > -1) {
          _this2.selectedElements.splice(index, 1);
        }

        _this2.trigger("deselected", id);
      }); // Determine if notation must be highlighted

      var api_opts = textData["url"].split("/").pop();

      if (api_opts.includes("highlight")) {
        new _highlightView["default"]({
          "el": container,
          "model": this.MEIdata
        });
      }
    }
  }, {
    key: "clearSelection",
    value: function clearSelection() {
      var _iterator = _createForOfIteratorHelper(this.selectedElements),
          _step;

      try {
        for (_iterator.s(); !(_step = _iterator.n()).done;) {
          var sel = _step.value;
          var $sel = this.$el.find("#" + sel);
          var class_att = $sel.attr("class");

          if (class_att) {
            var classes = class_att.split(" ");
            classes.splice(classes.indexOf(".cnt-selected"), 1);
            $sel.attr("class", classes.join(" "));
          }
        }
      } catch (err) {
        _iterator.e(err);
      } finally {
        _iterator.f();
      }

      this.interView.clearMusEvents();
      this.selectedElements = [];
      this.trigger("clearedSelection");
    }
  }, {
    key: "highlight",
    value: function highlight(ids) {
      this.highlightedElements = ids;
      this.renderPage(this.page);
    }
  }, {
    key: "clearHighlight",
    value: function clearHighlight() {
      this.highlightedElements = [];
      this.renderPage(this.page);
    }
  }, {
    key: "render",
    value: function render() {
      var _this3 = this;

      var container = (0, _jquery["default"])("<div class='cnt-container'></div>");
      this.$el.append(container); // Create EMA floating box

      this.EMAComponent = new _EMAexpr["default"]();
      container.append(this.EMAComponent.render());
      this.listenTo(this.EMAComponent, 'component:emaBox:clear', this.clearSelection);

      if (this.paginate && this.showPageCtrls) {
        // Create pagination floating box
        container.append(new _pagination["default"]().render());
      }

      if (this.meiString) {
        this.addFile({
          "filename": "",
          "url": "",
          "string": this.meiString
        });
      } else if (this.mei) {
        var url = this.mei;

        if (this.omas) {
          url = this.omas + encodeURIComponent(this.mei) + "/all/all/@all";
        }

        _jquery["default"].ajax({
          url: url,
          type: 'GET',
          dataType: 'text',
          success: function success(data) {
            _this3.addFile({
              "filename": _this3.mei,
              "url": _this3.mei,
              "string": data
            });
          }
        });
      }

      return this.$el;
    }
  }, {
    key: "renderPage",
    value: function renderPage(page) {
      if (page > 0 && page <= this.vrvToolkit.getPageCount()) {
        this.page = page;
        var svg = this.vrvToolkit.renderPage(page);
        var ext_svg = (0, _verovioExt["default"])(svg);
        this.$el.find(".cnt-container > svg").replaceWith(ext_svg); // Highlight ids

        var _iterator2 = _createForOfIteratorHelper(this.selectedElements),
            _step2;

        try {
          for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
            var id = _step2.value;
            var $mei_el = this.$el.find("#" + id);

            if (!$mei_el.hasClass("cnt-selected")) {
              $mei_el.addClass("cnt-selected");
            }
          }
        } catch (err) {
          _iterator2.e(err);
        } finally {
          _iterator2.f();
        }

        var _iterator3 = _createForOfIteratorHelper(this.highlightedElements),
            _step3;

        try {
          for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
            var _id = _step3.value;

            var _$mei_el = this.$el.find("#" + _id);

            if (!_$mei_el.hasClass("cnt-highlighted")) {
              _$mei_el.addClass("cnt-highlighted");
            }
          }
        } catch (err) {
          _iterator3.e(err);
        } finally {
          _iterator3.f();
        }
      }
    }
  }]);

  return Continuo;
}(Backbone.View); // Make main class available to pre-ES6 browser environments


if (window) {
  window.Continuo = Continuo;
}

var _default = Continuo;
exports["default"] = _default;