import React from 'react'
import {doAction} from './api'


class Controls extends React.Component {
  save = () => {
    const {css, js, content} = this.props
    doAction('save', {css, js, content}).then(() => {
      this.props.mergeState({changed: false})
    }).catch(alert)
  }

  commit = () => {
    const {css, js, content} = this.props
    doAction('commit', {css, js, content}).then(() => {
      this.props.mergeState({changed: false, commited: true})
    }).catch(alert)
  }

  publish = () => {
    doAction('publish').then(() => {
      this.props.mergeState({published: true})
    }).catch(alert)

  }
  unpublish = () => {
    doAction('unpublish').then(() => {
      this.props.mergeState({published: false})
    }).catch(alert)
  }
  render() {
    const {name, _id, categories, published, error, changed, remote, commited} = this.props
    const canSave = changed && !error.exists()
    const canCommit = !commited && !error.exists()
    return (
      <div style={{display: 'flex', justifyContent: 'space-between', height: 20}}>
        <div>{`Block name: ${name}`}</div>
        <div>{`Block id: ${_id}`}</div>
        <div>{`Block categories: ${categories}`}</div>
        <div style={{flexAlign: 'left'}}>
          {remote || <button onClick={this.save} disabled={!canSave}>Save</button>}
          <button onClick={this.commit} disabled={!canCommit}>Commit</button>
          {published
            ? <button onClick={this.unpublish}>Unpublish</button>
            : <button onClick={this.publish}>Publish</button>
          }
        </div>
      </div>
    )
  }
}

export default Controls
