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

export interface ToolbarResponsivePriorityStateParams {
  responsive: ToolbarResponsiveState;
  expandedWidth?: number;
  collapsedWidth?: number;
}

export class ToolbarResponsivePriorityState {
  readonly responsive: ToolbarResponsiveState;

  expandedWidth: number;
  collapsedWidth: number;

  _shouldShrink = false;

  _groupElement: HTMLElement | null = null;

  constructor(params: ToolbarResponsivePriorityStateParams) {
    this.expandedWidth = params.expandedWidth ?? 0;
    this.collapsedWidth = params.collapsedWidth ?? 0;

    this.responsive = params.responsive;

    makeObservable(this, {
      _shouldShrink: observable.ref,
      _syncWidth: action,
    });
  }

  _syncWidth() {
    const { _groupElement, _shouldShrink, responsive } = this;
    if (responsive.responsiveDisabled) {
      return;
    }
    if (!_groupElement) {
      return;
    }
    const measured = _groupElement.scrollWidth;
    if (_shouldShrink) {
      this.collapsedWidth = measured;
    } else {
      this.expandedWidth = measured;
    }
    responsive._scheduleRecompute();
  }
}
