import {Display} from './display.js'
import intro from './intro.js'

const state = {items: [], show: null, links: [] }

import {items} from './data.js'

for (let i = 0; i < items.length; ++i) {
  let item = items[i]
  item.id = i
  item.state = 'face-down'
  state.items.push(item)
}

class Actions {
  flip(id) {
    state.items[id].state = 'face-up'
  }
  show(id) {
    state.show = id
  }
  reset() {
    state.show = null
  }
  link(from, to) {
    if (from == to) return false
    const ok = state.items[from].linkable.filter(i => state.items[to].linkable.includes(i)).length > 0
    if (!ok) return false
    state.links.push({id: state.links.length, from, to})
    return true
  }
}
const actions = new Actions

let display
const dispatch = target => {
  let ret
  if (target.action) {
    ret = actions[target.action](target.from, target.to)
  } else {
    const match = target.match(/\/([^/]+)\/([^/]+)/)
    if (match && Object.hasOwnProperty.call(Actions.prototype, match[2])) {
      ret = actions[match[2]](match[1])
    } else actions.reset()
  }
  display.render(state)
  return ret
}
window.onpopstate = e => {
  dispatch(document.location.search)
}
display = new Display(dispatch, document.body.firstChild)

if (document.location.search) dispatch(document.location.search)
else display.renderIntro(intro)
