import React, { useState, useEffect, useRef } from 'react'
import PropTypes from 'prop-types'
import { Block } from '../ADLayout'

/**
 * @component
 */
function ADBlock (props) {
  const domBlock = useRef()
  const [block, setBlock] = useState(new Block({ ...props }))
  useEffect(() => {
    if (!block) setBlock(new Block({ ...props }, domBlock.current))
  }, [])

  useEffect(() => {
    if (block) {
      block.update(props)
    }
  }, [props])

  useEffect(() => {
    block.select(props.selected)
  }, [props.selected])
  return <div ref={domBlock} className='block'>{props.children}</div>
}

ADBlock.propTypes = {
  /**
   * x軸位置，單位px
   */
  x: PropTypes.number,
  /**
   * y軸位置，單位px
   */
  y: PropTypes.number,
  /**
   * 寬度，單位px
   */
  width: PropTypes.number,
  /**
   * 高度，單位px
   */
  height: PropTypes.number,
  /**
   * 背景色彩，css格式
   */
  backgroundColor: PropTypes.string,
  /**
   * 選取該block
   */
  selected: PropTypes.bool,
  /**
   * 子物件，任何可被render的element皆可
   */
  children: PropTypes.arrayOf(PropTypes.element)
}

ADBlock.defaultProps = {
  x: 0,
  y: 0,
  width: 100,
  height: 100,
  selected: false,
  backgroundColor: '#FFF'
}

export default ADBlock
