import { urlJoinParams } from './url'
import { promisifyAll } from 'miniprogram-api-promise'

function createNavigatorFn(fnName) {
  return function ({ pageId, packageName, params, mode='', events, success, fail, complete }) {
    let url;
    if(mode == 'plugin'){
      url = `plugin://${packageName}/${pageId}`
    } else if(mode ==='web'){
      console.warn(`${fnName} url can only be used in h5 build`);
      return;
    } else {
      pageId = pageId ? pageId.replace(/^(\.)?\//,'') : pageId;
      url = packageName
      ? `/${packageName}/pages/${pageId}/index`
        : `/pages/${pageId}/index`
    }

    if (fnName === 'navigateTo') {
      navigateToFn(urlJoinParams(url, params), { events, success, fail, complete});
      return;
    }

    wx[fnName]({
      url: urlJoinParams(url, params),
      events,
      success,
      fail,
      complete
    })
  }
}

/**
 * 页面堆栈10以内使用wx.navigateTo，超过10则使用wx.redirectTo
 * @param url
 * @param param1
 * @returns
 */
 function navigateToFn(url, { events, success, fail, complete}) {
  const pages = getCurrentPages();
  if(pages && pages.length >= 10) {
    wx.redirectTo({
      url,
      success,
      fail,
      complete
    });
    return;
  }

  wx.navigateTo({
    url,
    // @types/weixin-app@2.9.3没有events的定义，但实际上官方文档有：https://developers.weixin.qq.com/miniprogram/dev/api/route/wx.navigateTo.html
    // @ts-ignore
    events,
    success,
    fail,
    complete
  });
}

const navigateTo = createNavigatorFn('navigateTo')
const reLaunch = createNavigatorFn('reLaunch')
const redirectTo = createNavigatorFn('redirectTo')

export const wxp = {}
promisifyAll(wx, wxp)

export default {
  ...wxp,
  navigateTo,
  reLaunch,
  redirectTo,
  auth: undefined
}
