import Component from 'ember-component';
import { assert } from 'ember-metal/utils';
import $ from 'jquery';

export default Component.extend({

  hasReadAgreement: false,
  init() {
    this._super(...arguments);
    assert(`${ this } requires argument "closeAmendmentModal"`, typeof this.get('closeAmendmentModal') === 'function');
  },

  didInsertElement() {
    this._super(...arguments); // important!

    this.addEventListener('.contract-amendments-window', 'scroll', e => {
      if (this.get('hasReadAgreement')) { return; }

      let $contractWindow = $(e.target);
      let $wrapper = $contractWindow.find('.contract-amendments-wrapper');
      let margin = $contractWindow.innerHeight() - $contractWindow.height();
      let distanceToViewportTop = margin + $wrapper.height() - $contractWindow.height();
      let distanceToBottom =  $contractWindow.scrollTop() - distanceToViewportTop;
      let isScrolledToBottom = distanceToBottom < 1;

      if (!isScrolledToBottom) { return; }

      this.set('hasReadAgreement', true);
    });
  },

  actions: {
    accept() {
      this.get('closeAmendmentModal')(true);
    },
    cancel() {
      this.get('closeAmendmentModal')(false);
    }
  }
});
