import React, { Component } from 'react'
import classnames from 'classnames'
import './index.css'

export default class ImageCycle extends Component {
  constructor(props) {
    super(props)
    this.state = {
      i1: 0,
      i2: 1,
      mobile: true,
      mounted: false
    }
    this.imageList = props.imageList
    if (this.imageList && this.imageList.length % 2 !== 0) {
      this.imageList.push(this.imageList[Math.floor(this.imageList.length / 2)])
    }
    this.length = this.imageList.length
    this.changeImg1 = this.changeImg1.bind(this)
    this.changeImg2 = this.changeImg2.bind(this)
    this.handleWindowResize = this.handleWindowResize.bind(this)
  }
  componentDidMount() {
    this.timer2 = setInterval(this.changeImg2, 5000)
    this.timer1 = setTimeout(() => {
      this.changeImg1()
      this.timer3 = setInterval(this.changeImg1, 5000)
    }, 2500)
    window.addEventListener('resize', this.handleWindowResize)
    this.handleWindowResize()
    this.setState({
      mounted: true
    })
  }
  handleWindowResize() {
    this.setState({
      mobile: document.body.offsetWidth < 780
    })
  }
  componentWillUnmount() {
    window.removeEventListener('resize', this.handleWindowResize)
    clearTimeout(this.timer1)
    clearInterval(this.timer2)
    clearInterval(this.timer3)
  }
  changeImg1() {
    this.setState({
      i1: (this.state.i1 + 2) % this.length
    })
  }
  changeImg2() {
    this.setState({
      i2: (this.state.i2 + 2) % this.length
    })
  }
  render() {
    const { i1, i2, mobile, mounted } = this.state
    return (
      <div className="image-text-column-col2">
        {this.imageList.map((img, idx) => (
          <div
            key={idx}
            className={classnames({
              'image-cycle-image-show': i1 === idx || i2 === idx,
              'image-cycle-image1': idx % 2 === 0,
              'image-cycle-image2': idx % 2 === 1,
              'image-cycle-image-placeholder': true
            })}
            style={{
              backgroundImage: !mounted
                ? 'none'
                : `url(${mobile ? img.image1 : img.image1_2})`
            }}
          ></div>
        ))}
        <div className="image-cycle-mask1"></div>
        <div className="image-cycle-mask2"></div>
        <div className="clear"></div>
      </div>
    )
  }
}
