import { h, Component } from 'preact'
import { isMobile } from '../util'
import db from '../db'
import { Link, withRouter } from 'react-router-dom'

import Header from './Header.jsx'
import Paintings from './Paintings.jsx'
import Details from './Details.jsx'
import Modal from './Modal.jsx'

class App extends Component {
  constructor(props) {
    super()
    this.state = {
      data: db.backupDB,
      painting: null,
    }
    db.fetch( data => {
      document.body.parentNode.classList.remove('loading')
      this.setState({ data }) 
    })
  }
  setIdFromLocation(props){
    const id = props.location.pathname.split('/')[2]
    if (id) {
      this.setState({ painting: id })
    }
  }
  componentWillMount(){
    this.setIdFromLocation(this.props)
  }
  componentWillReceiveProps(props){
    this.setIdFromLocation(props)
  }
  render() {
    let painting;
    this.state.data.painting.some( (el) => {
      if (el.id == this.state.painting) {
        painting = el
        return true
      }
      return false
    })
    return (
      <div>
        <Header location={this.props.location} />
        <Paintings data={this.state.data} />
        <Modal visible={this.props.location.pathname !== '/paintings/'}>
          <Details painting={painting} />
        </Modal>
      </div>
    )
  }
}

export default withRouter(App)