import React, {Component} from 'react'
import styled from 'styled-components'
import auto_bind from 'common/auto_bind'
import event_system from 'common/event_system'

export default class Column extends Component {
  constructor(props) {
    super(props)
    this.state = {
      width: 500,
    }
    auto_bind(this)
  }

  componentDidMount() {
    this.update_width()
    this.cancel_update_width = event_system.register("window_resize", this.update_width)
  }

  componentWillUnmount() {
    this.cancel_update_width()
  }

  update_width() {
    const {offsetWidth: width} = this.background
    if (width != this.state.width) {
      this.setState({width})
    }
  }

  render() {
    const {className, children} = this.props
    const {width} = this.state
    return (
      <Background innerRef={(background) => this.background = background} className={className}>
        <Container max_width={Math.min(width - 20, 1000)}>
          {children}
        </Container>
      </Background>
    )
  }
}

const Background = styled.div`
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: stretch;
`
const Container = styled.div`
  max-width: ${({max_width}) => max_width}px;
  flex: 1;
  display: flex;
  align-items: stretch;
  flex-direction: column;
  padding: 10px;
`
