export default class WsContentEditableController {
  static $inject = ['$sce', '$scope', '$element', '$attrs'];
  constructor($sce, $scope, $element, $attrs) {
    this.$sce = $sce;
    this.$scope = $scope;
    this.$element = $element;
    this.$attrs = $attrs;
  }

  $postLink = () => {
    if (!this.ngModelCtrl) return;

    this.ngModelCtrl.$render = () => {
      this._updateDOMFromModelValue();
      this._updateModelFromDOMValue();
    };

    this.$element.on('blur keyup change', () => {
      this.$scope.$evalAsync(this._updateModelFromDOMValue);
    });
  }

  $onDestroy = () => {
    this.$element.off('blur keyup change', () => {
      this.$scope.$evalAsync(this._updateModelFromDOMValue);
    });
  }

  _updateModelFromDOMValue = () => {
    this.ngModelCtrl.$setViewValue(this.$element.html());
  }

  _updateDOMFromModelValue = () => {
    this.$element.html(this.$sce.getTrustedHtml(this.ngModelCtrl.$viewValue || ''));
  }
}
