# frozen_string_literal: true

require_relative "simple_swap"

class AltTopUpForm
	def self.for(customer)
		EMPromise.all([
			customer.btc_addresses,
			customer.bch_addresses
		]).then do |(btc, bch)|
			AltTopUpForm.new(customer, btc, bch)
		end
	end

	def initialize(customer, btc_addresses, bch_addresses)
		@customer = customer
		@balance = customer.balance
		@currency = customer.currency
		@btc_addresses = btc_addresses
		@bch_addresses = bch_addresses
	end

	def form
		FormTemplate.render(
			"alt_top_up",
			balance: @balance,
			currency: @currency,
			btc_addresses: @btc_addresses,
			bch_addresses: @bch_addresses
		)
	end

	def parse(form)
		action =
			form.field("http://jabber.org/protocol/commands#actions")&.value.to_s
		case action
		when "BTC", "BCH"
			ADD_ADDR.fetch(action).new(@customer)
		when /\A[A-Z]{3}\Z/
			SimpleSwapAddress.new(@customer, action, @bch_addresses.first)
		else
			NoOp.new
		end
	end

	class NoOp
		def action(*); end
	end

	class BitcoinAddress
		def initialize(customer)
			@customer = customer
		end

		def action(reply)
			@customer.add_btc_address.then do |addr|
				reply.command << FormTemplate.render(
					"alt_top_up/btc",
					btc_addresses: [addr]
				)
			end
		end
	end

	class BitcoinCashAddress
		def initialize(customer)
			@customer = customer
		end

		def action(reply)
			@customer.add_bch_address.then do |addr|
				reply.command << FormTemplate.render(
					"alt_top_up/bch",
					bch_addresses: [addr]
				)
			end
		end
	end

	class SimpleSwapAddress
		def initialize(customer, currency, bch_address, simple_swap: SimpleSwap.new)
			@customer = customer
			@currency = currency.downcase
			@bch_address = bch_address
			@simple_swap = simple_swap
		end

		def bch_address
			@bch_address || @customer.add_bch_address
		end

		def action(reply)
			EMPromise.resolve(bch_address).then { |bch|
				@simple_swap.fetch_addr(@currency, bch)
			}.then do |addr|
				reply.command << FormTemplate.render(
					"alt_top_up/simpleswap",
					addresses: [addr]
				)
			end
		end
	end

	ADD_ADDR = {
		"BTC" => BitcoinAddress,
		"BCH" => BitcoinCashAddress
	}.freeze
end
