/* 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.Registrations;

public class RegistrationStatusExample {
	/*
	 * Simple query of statuses a re-fetch of first status by entity id.
	 */
	@Test
	public void testRegistrationStatus() 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 and GET based on reference URI.
		 */
		Registration reg = regs.getList().get(0);
		target = client.target(reg.getLink().getHref());
		response = target.request(MediaType.APPLICATION_XML).get();
		Common.checkError(response);

		reg = response.readEntity(Registration.class);
		System.out.println("Recieved status for user login: " + reg.getLogin());
		System.out.println("Controller (no controller means not actice registration): " + reg.getController());
		System.out.println("Primary controller: " + reg.getPrimName());

		/*
		 * Now get the status via a query.
		 */
		String login = reg.getLogin();
		target = client.target(Common.URLBASE).path("registrations").queryParam("login", login)
				.queryParam("limit", "1");
		response = target.request(MediaType.APPLICATION_XML).get();
		Common.checkError(response);

		regs = response.readEntity(Registrations.class);
		System.out.println("Recieved " + regs.getCount() + " of " + regs.getTotalcount() + " statuses");

	}
}
