import React, {Component} from 'react'
import {MdReplay} from 'react-icons/lib/md'
import styled from 'styled-components'
import Field from 'components/field'
import {link, rotate} from 'common/styles'
import auto_bind from 'common/auto_bind'

export default class ComputedField extends Component {
  constructor(props) {
    super(props)
    this.state = {
      value: "",
      updating: false,
    }
    auto_bind(this)
  }

  static defaultProps = {
    show_label: true,
    fetch_value() {
      return new Promise((resolve, reject) => resolve(""))
    },
  }

  componentDidMount() {
    this.update_value()
  }

  componentDidReceiveProps() {
    this.update_value()
  }

  update_value() {
    this.setState({updating: true})
    this.props.fetch_value()
    .then((value) => this.setState({
      value,
      updating: false,
    }))
  }

  render() {
    const {value, updating} = this.state
    return (
      <Field {...this.props} category="computed">
        <Content>
          <ComputedValue>
            {value}
          </ComputedValue>
          <UpdateValue onClick={this.update_value} updating={updating}>
            <IconContainer updating={updating}>
              <MdReplay />
            </IconContainer>
          </UpdateValue>
        </Content>
      </Field>
    )
  }
}

const Content = styled.div`
  padding: 8px;
  display: flex;
  align-items: center;
`
const ComputedValue = styled.div`
  flex: 1;
`
const UpdateValue = styled.div`
  flex-shrink: 0;
  margin-left: 10px;
  padding: 5px;
  ${link}
`
const IconContainer = styled.div`
  height: 20px;
  width: 20px;
  display: flex;
  align-items: center;
  font-size: 16px;
  justify-content: center;
  ${({updating}) => updating ? rotate : ''}
`
