import { TableTopNotificationState } from './TableTopNotificationState';
import { action, makeObservable } from 'mobx';

export class ScrollAwayPushStrategy {
  state;
  constructor(state: TableTopNotificationState) {
    this.state = state;
    makeObservable(this, {
      switchToSticky: action.bound,
      switchToInline: action.bound,
      onIntersectionRatioChanged: action.bound,
    });
  }

  switchToSticky() {
    const {
      consideredVisibleRatio,
      intersection: { intersectionRatio },
      position,
    } = this.state;

    if (position !== 'sticky' && intersectionRatio < consideredVisibleRatio) {
      this.state.position = 'sticky';
    }
  }

  switchToInline() {
    this.state.position = 'inline';
  }

  onIntersectionRatioChanged(ratio: number) {
    const { position, consideredVisibleRatio } = this.state;
    if (position === 'sticky' && ratio >= consideredVisibleRatio) {
      this.state.position = 'inline';
    }
  }

  init() {
    const { topNotification } = this.state;
    topNotification.events.on('enter', this.switchToSticky);
    topNotification.events.on('beforeExit', this.switchToSticky);
    topNotification.events.on('exited', this.switchToInline);

    return () => {
      topNotification.events.off('enter', this.switchToSticky);
      topNotification.events.off('beforeExit', this.switchToSticky);
      topNotification.events.off('exited', this.switchToInline);
    };
  }
}
