import computed from 'ember-computed';
import getOwner from 'ember-owner/get';
import { assert } from 'ember-metal/utils';

/*
 * Calculate the correct number of items to appear in a row. This is commonly
 * used with the "tower" layout tools.
 *
 * See:
 *
 *   * https://git-aws.internal.justin.tv/pages/web/styles/tower.html
 *   * https://git-aws.internal.justin.tv/web/styles/releases/tag/v0.15.0
 *
 * Usage:
 *
 *     import limitForDirectoryTower from 'web-client/utilities/tower';
 *     import { CHANNEL_PREVIEW_MIN_WIDTH } from 'web-client/services/layout';
 *
 *     export default Component.extend({
 *       limitForOneRow: limitForDirectoryTower({
 *         minWidth: CHANNEL_PREVIEW_MIN_WIDTH
 *       }),
 *       limitForTwoRows: limitForDirectoryTower({
 *         minWidth: CHANNEL_PREVIEW_MIN_WIDTH,
 *         rowCount: 2
 *       })
 *     });
 *
 */
export default function limitForDirectoryTower({minWidth, rowCount}) {

  return computed('layout.contentWidth', 'towerOverride', function() {
    let towerOverride = this.get('towerOverride');
    if (towerOverride) { return towerOverride; }
    if (rowCount === undefined) {
      rowCount = 1;
    }
    assert('limitForDirectoryTower requires minWidth as a property on options', minWidth);
    let layout = this.get('layout');
    if (!layout) {
      layout = getOwner(this).lookup('service:layout');
      this.set('layout', layout);
    }
    let directoryWidth = layout.get('contentWidth');

    let countForRow = Math.floor(directoryWidth / minWidth);
    return countForRow * rowCount;
  });
}
