import Component from 'ember-component';
import { schedule } from 'ember-runloop';

/*
This component calculates pane widths for the channel feed.
The chunk pane needs to grow in whole grid units at a time,
so the flex pane grows between 1 and 2 units, and when a
whole unit is available, the chunk pane uses it, causing
the flex pane to shrink back down to 1 unit.

1 <= flex width < 2
chunk width is always an integer

------------------------------------------
|                 |                      |
|                 |                      |
|      Flex       |         Chunk        |
|      1.6gU      |         3gU          |
|                 |                      |
|                 |                      |
------------------------------------------

---------------------------------------------
|               |                           |
|               |                           |
|      Flex     |         Chunk             |
|      1gU      |         4gU               |
|               |                           |
|               |                           |
---------------------------------------------

When there are less than 2 units available, the layout will
not be split into panes.

*/
export default Component.extend({
  // gridUnit size in pixels
  gridUnit: 320,
  // pixels between flex and chunk panes
  divider: 30,
  // pixels between gridUnits in chunk pane specifically for panels on the channel page
  panelGutter: 20,

  didUpdateAttrs() {
    this._super(...arguments);
    schedule('afterRender', this, 'reflow');
  },

  didInsertElement() {
    this._super(...arguments);
    this.reflow();

    this.addEventListener(window, 'resize', () => {
      schedule('afterRender', this, 'reflow');
    });
  },

  reflow() {
    let { width } = this.element.getBoundingClientRect();
    let gridUnit = this.get('gridUnit');
    let divider = this.get('divider');
    let panelGutter = this.get('panelGutter');
    let flex = width;
    let chunk = width;

    // Units is the number of gridUnits that can fit in the total width with dividers between them.
    let units = Math.floor((width + divider) / (gridUnit + divider));
    let isSplit = units >= 2;
    if (isSplit) {
      chunk = (units - 1) * gridUnit + Math.max(0, units - 2) * panelGutter;
      flex = width - (chunk + divider);
    }

    this.set('isSplit', isSplit);
    this.set('flexWidth', flex);
    this.set('chunkWidth', chunk);
    this.set('columns', units);
  }
});
