function extendMethod(...fns) {
  return function (...args) {
    fns.forEach(
      fn => (typeof fn === 'function' ? fn.bind(this)(...args) : null),
    )
  }
}

function shareView(app) {
  app.onLoad = extendMethod(app.onLoad, function() {
    this.setData({
      showShareVariation: false,
      shareAnimation: {},
    })
  })

  app.onShow = extendMethod(app.onShow, function() {
    this.closeShareView()
  })

  // hack the onShareAppMessage whose options always is undefined
  app.closeShareView = extendMethod(function() {
    wx.showShareMenu()

    const animation = wx.createAnimation({
      duration: 400,
      timingFunction: 'ease',
    })
    this.setData({
      showShareVariation: false,
      shareAnimation: animation
        .translateY('100%')
        .step()
        .export(),
    })
  })

  app.openShareView = extendMethod(function() {
    wx.hideShareMenu()

    const animation = wx.createAnimation({
      duration: 400,
      timingFunction: 'ease',
    })

    this.setData({
      showShareVariation: true,
      shareAnimation: animation
        .translateY(0)
        .step()
        .export(),
    })
  })

  return app
}

export default shareView
