1# frozen_string_literal: true
  2
  3require_relative "simple_swap"
  4
  5class AltTopUpForm
  6	def self.for(customer)
  7		EMPromise.all([
  8			customer.btc_addresses,
  9			customer.bch_addresses
 10		]).then do |(btc, bch)|
 11			AltTopUpForm.new(customer, btc, bch)
 12		end
 13	end
 14
 15	def initialize(customer, btc_addresses, bch_addresses)
 16		@customer = customer
 17		@balance = customer.balance
 18		@currency = customer.currency
 19		@btc_addresses = btc_addresses
 20		@bch_addresses = bch_addresses
 21	end
 22
 23	def form
 24		FormTemplate.render(
 25			"alt_top_up",
 26			balance: @balance,
 27			currency: @currency,
 28			btc_addresses: @btc_addresses,
 29			bch_addresses: @bch_addresses
 30		)
 31	end
 32
 33	def parse(form)
 34		action =
 35			form.field("http://jabber.org/protocol/commands#actions")&.value.to_s
 36		case action
 37		when "BTC", "BCH"
 38			ADD_ADDR.fetch(action).new(@customer)
 39		when /\A[A-Z]{3}\Z/
 40			SimpleSwapAddress.new(@customer, action, @bch_addresses.first)
 41		else
 42			NoOp.new
 43		end
 44	end
 45
 46	class NoOp
 47		def action(*); end
 48	end
 49
 50	class BitcoinAddress
 51		def initialize(customer)
 52			@customer = customer
 53		end
 54
 55		def action(reply)
 56			@customer.add_btc_address.then do |addr|
 57				reply.command << FormTemplate.render(
 58					"alt_top_up/btc",
 59					btc_addresses: [addr]
 60				)
 61			end
 62		end
 63	end
 64
 65	class BitcoinCashAddress
 66		def initialize(customer)
 67			@customer = customer
 68		end
 69
 70		def action(reply)
 71			@customer.add_bch_address.then do |addr|
 72				reply.command << FormTemplate.render(
 73					"alt_top_up/bch",
 74					bch_addresses: [addr]
 75				)
 76			end
 77		end
 78	end
 79
 80	class SimpleSwapAddress
 81		def initialize(customer, currency, bch_address, simple_swap: SimpleSwap.new)
 82			@customer = customer
 83			@currency = currency.downcase
 84			@bch_address = bch_address
 85			@simple_swap = simple_swap
 86		end
 87
 88		def bch_address
 89			@bch_address || @customer.add_bch_address
 90		end
 91
 92		def action(reply)
 93			EMPromise.resolve(bch_address).then { |bch|
 94				@simple_swap.fetch_addr(@currency, bch)
 95			}.then do |addr|
 96				reply.command << FormTemplate.render(
 97					"alt_top_up/simpleswap",
 98					addresses: [addr]
 99				)
100			end
101		end
102	end
103
104	ADD_ADDR = {
105		"BTC" => BitcoinAddress,
106		"BCH" => BitcoinCashAddress
107	}.freeze
108end