import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Carousel from 'nuka-carousel';
import SlideNext from './SlideNext';
import SlidePrevious from './SlidePrevious';
import BottomSlider from './BottomSlider';

const propTypes = {
  /** @ignore */
  children: PropTypes.node,
  /** @ignore */
  style: PropTypes.object,
  SlideNextDecorator: PropTypes.object,
  SlidePreviousDecorator: PropTypes.object,
  BottomDecorator: PropTypes.object,
  className: PropTypes.string
};

const defaultProps = {
  children: null,
  style: null,
  numberSlides: 1,
  slidesToScroll: 1,
  slidesToShow: 1,
  cellSpacing: 20,
  SlideNextDecorator: {
    component: SlideNext,
    position: 'TopRight'
  },
  SlidePreviousDecorator: {
    component: SlidePrevious,
    position: 'TopLeft'
  },
  BottomDecorator: {
    component: BottomSlider,
    position: 'BottomCenter'
  },
  className: undefined
};

class Slideshow extends Component {

  componentDidMount() {
    this.forceUpdate();
  }

  componentDidUpdate() {
    // fix: height is now set to the tallest children and not the first one
    if (this.childRefs[0]) {
      for (let index = 0; index < this.childRefs.length; index += 1) {
        if (this.childRefs[index + 1]) {
          if (this.childRefs[0].parentNode.offsetHeight < this.childRefs[index + 1].parentNode.offsetHeight) {
            this.childRefs[0].style.height = `${this.childRefs[index + 1].parentNode.offsetHeight}px`;
          }
        }
      }
    }
  }

  childRefs = [];

  render() {
    const {
      SlideNextDecorator, SlidePreviousDecorator, BottomDecorator, children, style, className, ...rest
    } = this.props;
    const carouselDecorators = [SlidePreviousDecorator, SlideNextDecorator, BottomDecorator];
    const childrenWithProps = React.Children.map(this.props.children,
      child => <div ref={node => this.childRefs.push(node)} >{child}</div>
    );
    return (
      <div itemScope >
        <Carousel
          decorators={carouselDecorators}
          style={style || { paddingTop: '25px', paddingBottom: '25px' }}
          ref={carousel => { this.carousel = carousel; }}
          beforeSlide={this.beforeSlide}
          className={className}
          {...rest}
        >
          {childrenWithProps}
        </Carousel>
      </div>
    );
  }
}


Slideshow.propTypes = propTypes;

Slideshow.defaultProps = defaultProps;

export default Slideshow;
