'use strict'
import { Application } from '../Application'
import TransformAnimation from './animation'

class TransformHistory extends TransformAnimation {
  private backoutCount: number = 0
  constructor (app: Application) {
    super(app)
    this.bindHistoryState()
  }

  private bindHistoryState () {
    addEventListener('popstate', this.popstate.bind(this))
  }

  public popstate (event: PopStateEvent) {
    this.back(event)
  }

  public pushState (id = '', title = '', search = location.search, param = '') {
    id = encodeURIComponent(id)
    history.pushState({
      id,
      title,
      time: Date.now(),
      search,
      historyIndex: history.length
    }, title, location.pathname + search + '#' + id + '/' + param)
  }

  public replaceState (id = '', title = '', search = location.search, param = '') {
    id = encodeURIComponent(id)
    history.replaceState({
      id,
      title,
      time: Date.now(),
      search,
      historyIndex: history.length
    }, title, location.pathname + search + '#' + id + '/' + param)
  }

  public async back (event: PopStateEvent) {
    const options = this.options
    const route = event.state || this.app.route
    const id = decodeURIComponent(route.id) || options.index || 'frameworks'
    const search = route.search
    const module = await this.app.get(id)
    if (!module) return
    /**
     * 如果设置了单向锁，且回退时模块层级为 0 时
     * 阻止返回，并发送事件
     */
    if (this.checkSingleLock()) {
      this.backoutCount++
      this.pushState(id, module.config.title, search)
      this.app.trigger('exit', {
        backoutCount: this.backoutCount
      })
      return
    } else {
      this.backoutCount = 0
    }

    if (options.singleFlow && module.config.level !== 0 && module.config.level >= this.module.config.level) {
      return history.back()
    }

    this.app.transform.to(id, search, -1)
    this.app.trigger('back', {
      id,
      module
    })
  }

  public checkSingleLock (): boolean {
    return this.options.singleLock && this.module.config.level === 0 ? true : false
  }
}

export default TransformHistory
