import { fly } from './fly'

async function tryWrapper(p, ...rest) {
  const wrapper = {
    error: false,
    data: null,
    result: {}
  }
  try {
    const result = await p(...rest)
    const { data = {} } = result
    wrapper.data = data
    wrapper.result = result
  } catch (error) {
    wrapper.error = true
    wrapper.result = error
  }
  return wrapper
}

const flyWrapper = (url, data, config, method) => {
  return fly.request(url, data, { ...config, method })
}

const request = {
  get(url, data, config) {
    return flyWrapper(url, data, config, 'GET')
  },
  post(url, data, config) {
    return flyWrapper(url, data, config, 'POST')
  },
  put(url, data, config) {
    return flyWrapper(url, data, config, 'PUT')
  },
  delete(url, data, config) {
    return flyWrapper(url, data, config, 'DELETE')
  },
  tryGet(...rest) {
    return tryWrapper(this.get, ...rest)
  },
  tryPost(...rest) {
    return tryWrapper(this.post, ...rest)
  },
  tryPut(...rest) {
    return tryWrapper(this.put, ...rest)
  },
  tryDelete(...rest) {
    return tryWrapper(this.delete, ...rest)
  }
}

// = (url, data, config) => {
// }

export default request
