/**
*
* CardGrid
*
*/

import PropTypes from 'prop-types';

import React from 'react';
import {CapSpin, CapRow, CapColumn} from '@capillarytech/cap-ui-library';
import CustomCard from '../Card';

class CardGrid extends React.Component { // eslint-disable-line react/prefer-stateless-function
  constructor(props) {
    super(props);
    this.handleOnItemHover = this.handleOnItemHover.bind(this);
    this.handleOnItemClick = this.handleOnItemClick.bind(this);
    this.delayTimer = 0;
  }

  handleOnItemHover(state, id) {
    this.delay(() => {
      this.props.onHoverItem(state, id);
    }, 200);
  }

  delay(callback, ms) {
    clearTimeout(this.delayTimer);
    this.delayTimer = setTimeout(callback, ms);
  }

  handleOnItemClick(state, id) {
    this.props.onItemClick(state, id);
  }

  render() {
    return (
      <div className={this.props.className}>
        <div style={{ marginBottom: '16px' }}>{this.props.filterContent}</div>
        <CapSpin spinning={this.props.isLoading} tip={this.props.loadingTip}>
          <div className={this.props.enablePagination ? 'v2-pagination-container' : ''}>
            <CapRow gutter={this.props.gutterSize}>
              { this.props.listItem.length > 0 ? this.props.listItem.map( (item) => (
                <CapColumn style={{ width: `${100 / this.props.colNumber}%`, paddingBottom: '16px'}} key={item.id} span={parseInt(24 / this.props.colNumber, 10)}>
                  <CustomCard id={item.id} onHover={this.handleOnItemHover} onClick={this.handleOnItemClick} content={item.content} footer={item.footer} height={item.footer ? "312px" : "258px"}></CustomCard>
                </CapColumn>
              )) : ''}
            </CapRow>
          </div>
        </CapSpin>

      </div>
    );
  }
}

CardGrid.propTypes = {
  listItem: PropTypes.array.isRequired,
  filterContent: PropTypes.element,
  colNumber: PropTypes.number,
  gutterSize: PropTypes.number,
  onHoverItem: PropTypes.func,
  onItemClick: PropTypes.func,
  className: PropTypes.string,
  enablePagination: PropTypes.bool,
  isLoading: PropTypes.bool,
  loadingTip: PropTypes.string,
};

CardGrid.defaultProps = {
  gutterSize: 16,
  colNumber: 4,
  className: '',
  isLoading: false,
};

export default CardGrid;
