/**
 * Created by baoyinghai on 5/26/17.
 */
import React from 'react';
import Bit from './Bit';
import { BIT, COLUMN_COUNT, LINE_COUNT } from '../../constant';


export const calculateHitBit = (cards = []) => {
  const hitArr = [];
  cards.forEach(({layout}) => {
    const { x, y, width, height } = layout;
    for (let i = x; i < x + width; i++) {
      for (let j = y; j < y + height; j++) {
        hitArr[i + j * COLUMN_COUNT] = true;
      }
    }
  });
  return hitArr;
};

export const isOccupy = (x, y, width, height, hitArr) => {
  if (x < 0 || y < 0) {
    return true;
  }
  if (x + width > COLUMN_COUNT || y + height > LINE_COUNT) return true;
  for (let i = y; i < y + height; i++) {
    for (let j = x; j < x + width; j++) {
      if (hitArr[j + i * COLUMN_COUNT]) {
        return true;
      }
    }
  }
  return false;
};

export const calculatePosition = (width, height, cards) => {
  const hitArr = calculateHitBit(cards);
  for (let y = 0; y < LINE_COUNT; y++) {
    for (let x = 0; x < COLUMN_COUNT; x++) {
      if (!isOccupy(x, y, width, height, hitArr)) {
        return {x, y};
      }
    }
  }
  throw new Error('没有空白区域了！');
};

export default class Board extends React.Component {

  renderBit = () => {
    const hitArr = calculateHitBit(this.props.cards);
    const ret = [];
    for(let i = 0; i < LINE_COUNT * COLUMN_COUNT ; i++) {
      ret.push(<Bit index={i} isHit={!!hitArr[i]} />) ;
    }
    return ret;
  };

  calculateLayout = () => {
    const { cards, model } = this.props;
    if (model !== 'view') {
      return { height: LINE_COUNT, width: COLUMN_COUNT };
    }
    let gHeight = 0,
      gWidth = 0;
    if (cards) {
      cards.forEach(card => {
        if (!card) return;
        const layout = card.layout;
        if (!layout) return;
        const { x, y, width, height } = layout;
        if (x == undefined || y === undefined || width === undefined || height === undefined) return;
        gHeight = Math.max(gHeight, y + height);
        gWidth =  Math.max(gWidth, x + width);
      });
    }
    return { height: Math.min(gHeight, LINE_COUNT), width: Math.min(gWidth, COLUMN_COUNT) };
  };

  render() {
    const { height, width } = this.calculateLayout();
    return (
      <div className="dash-board-wrapper" >
        <div className="dash-board" style={{width: BIT * width, height: Math.max(window.innerHeight - 80, BIT * height + 20)}}>
          {this.props.model === 'edit' && this.renderBit()}
          {this.props.children}
        </div>
      </div>
    );
  }
}