/*
 * Tigase Push - Push notifications component for Tigase
 * Copyright (C) 2017 Tigase, Inc. (office@tigase.com) - All Rights Reserved
 * Unauthorized copying of this file, via any medium is strictly prohibited
 * Proprietary and confidential
 */
package tigase.rest.push


import tigase.http.rest.Service
import tigase.kernel.beans.Bean
import tigase.kernel.beans.Inject
import tigase.server.Iq
import tigase.server.Packet
import tigase.vhosts.VHostManagerIfc
import tigase.xml.Element
import tigase.xml.XMLUtils
import tigase.xmpp.StanzaType

@Bean(name = "push-unregister-device", active = true)
class UnregisterDeviceHandler extends tigase.http.rest.Handler {

	def TIMEOUT = 30 * 1000;
	
	@Inject
	private VHostManagerIfc vHostManagerIfc;

	public UnregisterDeviceHandler() {
		description = [
		        regex: "/unregister-device/{component_jid}",
				POST : [
				        info: 'Unregister device for push notifications',
						description: """---"""
				]
		]
		regex = /\/unregister-device\/([^@\/]+)/
		isAsync = true
		apiKey = false
		authRequired = { key -> return false }

		execPost = { Service service, callback, Map content, String component ->
			if (!component) {
				callback(null);
				return;
			}
			if (!vHostManagerIfc.isLocalDomainOrComponent(component)) {
				callback(null);
				return;
			}

			if (content.account == null || (!(content.account instanceof String))) {
				callback(null);
				return;
			}
			if (content.provider == null || (!(content.provider instanceof String))) {
				callback(null);
				return;
			}
			if (content["device-token"] == null || (!(content["device-token"] instanceof String))) {
				callback(null);
				return;
			}

			Element iq = new Element("iq");
			iq.setXMLNS(Iq.CLIENT_XMLNS);
			iq.setAttribute("to", component);
			iq.setAttribute("from", content.account as String)
			iq.setAttribute("type", "set");
			iq.setAttribute("id", UUID.randomUUID().toString());

			iq.withElement("command", "http://jabber.org/protocol/commands", { commandEl ->
				commandEl.setAttribute("node", "unregister-device");
				commandEl.withElement("x", "jabber:x:data", { xEl ->
					xEl.setAttribute("type", "submit");

					xEl.withElement("field", { fieldEl ->
						fieldEl.setAttribute("var", "provider");
						fieldEl.withElement("value", null, XMLUtils.escape(content.provider as String));
					})

					xEl.withElement("field", { fieldEl ->
						fieldEl.setAttribute("var", "device-token");
						fieldEl.withElement("value", null, XMLUtils.escape(content["device-token"] as String));
					})
				})
			})

			service.sendPacket(new Iq(iq), TIMEOUT, { Packet result ->
				callback([result: result.type == StanzaType.result ? "success" : "failure"]);
			})
		}
	}
}
