import { LitElement } from 'lit-element'

import { connect } from 'pwa-helpers/connect-mixin.js'
import { store, navigate, authcheck, setRoute } from '../reducer/store'

export default class AuthRouter extends connect(store)(LitElement) {
  static get is() {
    return 'auth-router'
  }

  static get properties() {
    return {
      // statePath: 'route.page'
      page: String,
      // statePath: 'auth.user'
      token: String
    }
  }

  async firstUpdated() {
    /*
      authcheck를 서버에 요청해서, 인증 여부를 판단하고, 사용자 정보를 획득한다.
    */
    await store.dispatch(authcheck())
  }

  updated(change) {
    change.has('page') && this.onPageChanged()
    change.has('token') && this.onTokenChanged()
  }

  stateChanged(state) {
    this.page = state.route.page
    this.token = state.auth.token
  }

  onPageChanged(page = 'list-recent') {}

  onTokenChanged() {
    if (!this.token || (this.page !== 'signin' && this.page !== 'signup')) return

    var pathname = location.pathname
    const page = pathname === '/' ? 'list-recent' : pathname.split('/')[1]

    if (this.page == page) {
      store.dispatch(setRoute(''))
    } else {
      store.dispatch(navigate(pathname))
    }
  }
}

customElements.define(AuthRouter.is, AuthRouter)
