'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = require('react');

var _propTypes = require('prop-types');

var _propTypes2 = _interopRequireDefault(_propTypes);

var _reactIntl = require('react-intl');

var _immutable = require('immutable');

var _immutable2 = _interopRequireDefault(_immutable);

var _get = require('lodash/get');

var _get2 = _interopRequireDefault(_get);

var _cspaceRefname = require('cspace-refname');

var _notificationStatusCodes = require('../../constants/notificationStatusCodes');

var _refNameHelpers = require('../../../src/helpers/refNameHelpers');

var _relationListHelpers = require('../../../src/helpers/relationListHelpers');

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

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

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

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

var notificationID = 'hierarchyReparentNotifier';

var messages = (0, _reactIntl.defineMessages)({
  reparentWarning: {
    'id': 'hierarchyReparentNotifier.reparentWarning',
    'defaultMessage': '{childName} currently has the broader record {parentName}. Its broader record will be changed when this record is saved.'
  }
});

var propTypes = {
  config: _propTypes2.default.object.isRequired,
  csid: _propTypes2.default.string.isRequired,
  childData: _propTypes2.default.instanceOf(_immutable2.default.Map).isRequired,
  readRecord: _propTypes2.default.func.isRequired,
  removeNotification: _propTypes2.default.func.isRequired,
  showNotification: _propTypes2.default.func.isRequired
};

var HierarchyReparentNotifier = function (_Component) {
  _inherits(HierarchyReparentNotifier, _Component);

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

    return _possibleConstructorReturn(this, (HierarchyReparentNotifier.__proto__ || Object.getPrototypeOf(HierarchyReparentNotifier)).apply(this, arguments));
  }

  _createClass(HierarchyReparentNotifier, [{
    key: 'componentDidMount',
    value: function componentDidMount() {
      this.readRecords(this.props.childData.keySeq().filter(function (refName) {
        return !!refName;
      }));
      this.showNotification();
    }
  }, {
    key: 'componentDidUpdate',
    value: function componentDidUpdate(prevProps) {
      var childData = this.props.childData;
      var prevChildData = prevProps.childData;


      var newRefNames = childData.keySeq().filter(function (refName) {
        return refName && !prevChildData.has(refName);
      });

      this.readRecords(newRefNames);

      if (!childData.equals(prevChildData)) {
        this.showNotification();
      }
    }
  }, {
    key: 'readRecords',
    value: function readRecords(refNames) {
      var _props = this.props,
          config = _props.config,
          readRecord = _props.readRecord;


      refNames.forEach(function (refName) {
        var childRecordType = (0, _refNameHelpers.getRecordType)(config, refName);

        if (!childRecordType) {
          return;
        }

        var childVocabulary = (0, _refNameHelpers.getVocabulary)(config, refName);

        if (!childVocabulary) {
          return;
        }

        var childRecordTypeConfig = (0, _get2.default)(config, ['recordTypes', childRecordType]);
        var childVocabularyConfig = (0, _get2.default)(childRecordTypeConfig, ['vocabularies', childVocabulary]);
        var childCsid = (0, _refNameHelpers.refNameToCsid)(refName);

        readRecord(config, childRecordTypeConfig, childVocabularyConfig, childCsid);
      });
    }
  }, {
    key: 'showNotification',
    value: function showNotification() {
      var _props2 = this.props,
          csid = _props2.csid,
          childData = _props2.childData,
          removeNotification = _props2.removeNotification,
          showNotification = _props2.showNotification;


      var items = [];

      childData.forEach(function (data, childRefName) {
        if (!childRefName || !data) {
          return;
        }

        var childCsid = (0, _refNameHelpers.refNameToCsid)(childRefName);

        var relations = (0, _relationListHelpers.normalizeRelationList)(data.getIn(['document', 'rel:relations-common-list', 'relation-list-item']));

        if (!relations) {
          return;
        }

        var relation = (0, _relationListHelpers.findBroaderRelation)(childCsid, relations);

        if (relation) {
          var parentCsid = relation.getIn(['object', 'csid']);

          if (parentCsid && parentCsid !== csid) {
            var childName = (0, _cspaceRefname.getDisplayName)(childRefName);
            var parentName = (0, _cspaceRefname.getDisplayName)(relation.getIn(['object', 'refName']));

            items.push({
              message: messages.reparentWarning,
              values: {
                childName: childName,
                parentName: parentName
              }
            });
          }
        }
      });

      if (items.length > 0) {
        showNotification({
          items: items,
          date: new Date(),
          status: _notificationStatusCodes.STATUS_WARNING
        }, notificationID);
      } else {
        removeNotification(notificationID);
      }
    }
  }, {
    key: 'render',
    value: function render() {
      return null;
    }
  }]);

  return HierarchyReparentNotifier;
}(_react.Component);

exports.default = HierarchyReparentNotifier;


HierarchyReparentNotifier.propTypes = propTypes;
HierarchyReparentNotifier.notificationID = notificationID;