import clone from 'lodash.clonedeep'

export default class Router {
  constructor (comp, initialState) {
    this.component = comp
    this.initialState = clone(initialState)
    this.state = clone(initialState) || {}

    window.onpopstate = event => {
      const state = event.state
      if (state) {
        if (state.toDispatch) {
          this.component.dispatch(state.toDispatch)
        }
      }
    }
  }

  reset () {
    this.state = {
      zoom: this.state.zoom,
      sort: this.state.sort,
      bounds: this.state.bounds,
      rooms: {},
      category: {}
    }
    this.update({})
  }

  update (state) {
    const params = []
    if (state.params) {
      let cloned = clone(state)

      if (cloned.params.rooms != null) {
        this.state.rooms[cloned.params.rooms] = !this.state.rooms[
          cloned.params.rooms
        ]
      }

      if (cloned.params.category != null) {
        this.state.category[cloned.params.category] = !this.state.category[
          cloned.params.category
        ]
      }

      delete cloned.params['rooms']
      delete cloned.params['category']

      this.state = Object.assign(this.state, cloned.params)

      const {
        listingId,
        minPrice,
        maxPrice,
        minSize,
        maxSize,
        bounds,
        sort,
        rooms = {},
        category = {},
        zoom,
        adType
      } = this.state

      if (listingId) {
        params.push(`listingId=${listingId}`)
      }

      params.push(`adType=${adType}`);
      params.push(`sort=${sort}`)
      params.push(`bounds=${bounds}`)
      params.push(`zoom=${zoom}`)
      if (maxPrice) {
        params.push(`maxPrice=${maxPrice}`)
      }

      if (minPrice) {
        params.push(`minPrice=${minPrice}`)
      }

      if (minSize) {
        params.push(`minSize=${minSize}`)
      }

      if (maxSize) {
        params.push(`maxSize=${maxSize}`)
      }
      params.push(
        `rooms=${Object.keys(rooms).filter(v => rooms[v]).join(',')}`
      )
      params.push(
        `category=${Object.keys(category).filter(v => category[v]).join(',')}`
      )
    }

    if (state.toDispatch) {
      window.history.pushState(state, '', `/?${params.join('&')}`)
    } else {
      const oldState = window.history.state
      if (oldState) {
        const newState = Object.assign(oldState, state)
        window.history.replaceState(newState, '', `/?${params.join('&')}`)
      } else {
        window.history.replaceState(state, '', `/?${params.join('&')}`)
      }
    }
  }
}
