// 

import { primitives } from 'bcoin'

import parse from 'url-parse'

import { toLegacyFormat, toNewFormat } from '../utils/addressFormat.js'

const getSpendTargets = (
  outputs,
  network,
  currencyCode
) => {
  let nativeAmount = 0
  const spendTargets = []
  for (const output of outputs) {
    const jsonObj = output.getJSON(network)
    nativeAmount += jsonObj.value
    spendTargets.push({
      currencyCode: currencyCode,
      publicAddress: toNewFormat(jsonObj.address, network),
      nativeAmount: `${jsonObj.value}`
    })
  }
  return { nativeAmount, spendTargets }
}

const getBitPayPayment = async (
  paymentProtocolURL,
  network,
  currencyCode,
  fetch
) => {
  const headers = {
    Accept: 'application/payment-request',
    'x-currency': currencyCode
  }
  const result = await fetch(paymentProtocolURL, { headers })
  if (parseInt(result.status) !== 200) {
    const error = await result.text()
    throw new Error(error)
  }
  const paymentRequest = await result.json()
  const {
    outputs,
    memo,
    paymentUrl,
    paymentId,
    requiredFeeRate,
    currency
  } = paymentRequest
  const parsedOutputs = outputs.map(({ amount, address }) => {
    const legacyAddress = toLegacyFormat(address, network)
    return primitives.Output.fromOptions({
      value: amount,
      address: legacyAddress
    })
  })
  const { nativeAmount, spendTargets } = getSpendTargets(
    parsedOutputs,
    network,
    currency
  )
  const domain = parse(paymentUrl, {}).hostname
  // $FlowFixMe
  const edgePaymentProtocolInfo = {
    nativeAmount: `${nativeAmount}`,
    merchant: { paymentId, requiredFeeRate },
    memo,
    domain,
    spendTargets,
    paymentUrl
  }

  return edgePaymentProtocolInfo
}

export async function getPaymentDetails(
  paymentProtocolURL,
  network,
  currencyCode,
  fetch
) {
  return getBitPayPayment(paymentProtocolURL, network, currencyCode, fetch)
}

export function createPayment(
  paymentDetails,
  refundAddress,
  tx,
  currencyCode
) {
  return { currency: currencyCode, transactions: [tx] }
}

export async function sendPayment(
  fetch,
  network,
  paymentUrl,
  payment,
  log
) {
  const headers = { 'Content-Type': 'application/payment' }
  if (global.androidFetch) {
    try {
      const result = await global.androidFetch(paymentUrl, {
        method: 'POST',
        headers,
        body: JSON.stringify(payment)
      })
      const paymentACK = JSON.parse(result)
      return paymentACK
    } catch (e) {
      log.error(e)
      throw e
    }
  }
  const result = await fetch(paymentUrl, {
    method: 'POST',
    headers,
    body: JSON.stringify(payment)
  })
  if (parseInt(result.status) !== 200) {
    const error = await result.text()
    throw new Error(error)
  }
  const paymentACK = await result.json()
  return paymentACK
}
