/* Copyright 2017 Avaya LLC. All rights reserved. */
package sample;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.junit.Test;

import com.avaya.asm.mgmt.model.rs.Registration;
import com.avaya.asm.mgmt.model.rs.RegistrationNotifyStatus;
import com.avaya.asm.mgmt.model.rs.RegistrationNotifyStatuses;
import com.avaya.asm.mgmt.model.rs.Registrations;

public class RegistrationNotificationExample {
	/*
	 * Simple query of statuses a re-fetch of first status by entity id.
	 */
	@Test
	public void testRegistrationNotify() throws Exception {
		Client client = Common.getClient();

		/*
		 * Query all statuses.
		 */

		WebTarget target = client.target(Common.URLBASE).path("registrations");
		Response response = target.request(MediaType.APPLICATION_XML).get();
		if (response.getStatus() == 503) {
			// Registration cache not loaded, let's wait a bit.
			Thread.currentThread().sleep(15000);
			response = target.request(MediaType.APPLICATION_XML).get();
		}
		Common.checkError(response);

		/*
		 * In this case we are manually telling what entity type is to be
		 * unmarshalled. Many clients allow registration of the JAXB mapping
		 * classes so this is not needed.
		 */
		Registrations regs = response.readEntity(Registrations.class);
		System.out.println("Recieved " + regs.getCount() + " of " + regs.getTotalcount() + " statuses");
		for (Registration reg : regs.getRegistration()) {
			System.out.println("Recieved status for login: " + reg.getLogin());
		}

		/*
		 * Now take first status found send notification based on reference URI.
		 */
		Registration reg = regs.getList().get(0);
		target = client.target(reg.getLink().getHref()).queryParam("notify", "reboot");
		response = target.request(MediaType.APPLICATION_XML).post(null);
		Common.checkError(response);

		RegistrationNotifyStatuses statuses = response.readEntity(RegistrationNotifyStatuses.class);
		System.out.println("Requested " + statuses.getRequested() + " and sent " + statuses.getSent());

		/*
		 * Now send notification based on query.
		 */
		String login = reg.getLogin();
		target = client.target(Common.URLBASE).path("registrations").queryParam("login", login)
				.queryParam("notify", "reboot");
		response = target.request(MediaType.APPLICATION_XML).post(null);
		Common.checkError(response);

		statuses = response.readEntity(RegistrationNotifyStatuses.class);
		System.out.println("Requested " + statuses.getRequested() + " and sent " + statuses.getSent());
		for (RegistrationNotifyStatus status : statuses.getList()) {
			System.out.println(" For sm " + status.getStatusLink().getLink().getHrefName() + " requested "
					+ status.getRequested() + " sent " + status.getSent());
		}

	}
}
