# frozen_string_literal: true

require "blather"

module Snikket
	class Launch < Blather::Stanza::Iq
		register nil, "launch", "xmpp:snikket.org/hosting/v1"

		def self.new(type=nil, to=nil, id=nil, domain: nil)
			stanza = super(type || :set, to, id)
			node = Nokogiri::XML::Node.new("launch", stanza.document)
			node.default_namespace = registered_ns
			stanza << node
			stanza.domain = domain if domain
			stanza
		end

		def domain=(domain)
			query.at_xpath("./ns:domain", ns: self.class.registered_ns)&.remove
			node = Nokogiri::XML::Node.new("domain", document)
			node.default_namespace = self.class.registered_ns
			node.content = domain
			query << node
		end

		def query
			at_xpath("./ns:launch", ns: self.class.registered_ns)
		end
	end

	class Launched < Blather::Stanza::Iq
		register :snikket_launched, "launched", "xmpp:snikket.org/hosting/v1"

		def instance_id
			query
				.at_xpath("./ns:instance-id", ns: self.class.registered_ns)
				&.content
		end

		def bootstrap_token
			query
				.at_xpath("./ns:bootstrap/ns:token", ns: self.class.registered_ns)
				&.content
		end

		def bootstrap_uri(instance_domain)
			"https://#{instance_domain}/invites_bootstrap?token=#{bootstrap_token}"
		end

		def query
			at_xpath("./ns:launched", ns: self.class.registered_ns)
		end
	end

	class Instance < Blather::Stanza::Iq
		register :snikket_instance, "instance", "xmpp:snikket.org/hosting/v1"

		def self.new(type=nil, to=nil, id=nil, instance_id: nil)
			stanza = super(type || :get, to, id)
			node = Nokogiri::XML::Node.new("instance", stanza.document)
			node.default_namespace = registered_ns
			stanza << node
			stanza.instance_id = instance_id if instance_id
			stanza
		end

		def inherit(*)
			query.remove
			super
		end

		def instance_id=(instance_id)
			query.at_xpath("./ns:instance-id", ns: self.class.registered_ns)&.remove
			node = Nokogiri::XML::Node.new("instance-id", document)
			node.default_namespace = self.class.registered_ns
			node.content = instance_id
			query << node
		end

		def instance_id
			query
				.at_xpath("./ns:instance-id", ns: self.class.registered_ns)
				&.content
		end

		def update_needed?
			!!query.at_xpath("./ns:update-needed", ns: self.class.registered_ns)
		end

		def operation
			query.at_xpath("./ns:operation", ns: self.class.registered_ns)
		end

		def status
			query
				.at_xpath("./ns:status", ns: self.class.registered_ns)
				&.content&.to_sym
		end

		def query
			at_xpath("./ns:instance", ns: self.class.registered_ns)
		end
	end
end
