package com.agilex.healthcare.schedulingmanager.linkbuilder;

import java.net.URI;

import javax.ws.rs.core.UriBuilder;

import com.agilex.healthcare.mobilehealthplatform.domain.DomainTransferObject;
import com.agilex.healthcare.utility.NullChecker;
import com.agilex.healthcare.utility.NullSafeStringComparer;

public class UriHelper {
	public static void setSelfUri(DomainTransferObject dto, URI requestUri, URI canonicalSelfUri) {
		URI selfUri = null;
		URI alternateUri = null;

		if (requestUri != null && linksAreDifferent(requestUri, canonicalSelfUri)) {
			selfUri = requestUri;
			alternateUri = canonicalSelfUri;
		} else {
			selfUri = canonicalSelfUri;
		}

		if (selfUri != null) {
			dto.setSelfUri(selfUri);
		}

		if (alternateUri != null) {
			dto.getLink().addAlternateLink("canonical-self", alternateUri);
		}
	}

//	public static void setSelfUri(DomainTransferObjectCollection<?> dtoCollection, URI requestUri, URI canonicalSelfUri) {
//		if (requestUri != null && linksAreDifferent(requestUri, canonicalSelfUri)) {
//			dtoCollection.setSelfUri(requestUri);
//			dtoCollection.getLink().addAlternateLink("canonical-self", canonicalSelfUri);
//		} else {
//			dtoCollection.setSelfUri(canonicalSelfUri);
//		}
//	}

	private static boolean linksAreDifferent(URI requestUri, URI canonicalSelfUri) {
		return !linksAreSame(requestUri, canonicalSelfUri);
	}

	private static boolean linksAreSame(URI requestUri, URI canonicalSelfUri) {
		String l1 = requestUri.toString();
		String l2 = requestUri.toString();
		return NullSafeStringComparer.areEqual(l1, l2);
	}

	public static URI mergeUri(URI uri, String path) {
		URI mergedUri = null;
		if (uri == null) {
			mergedUri = null;
		} else if (NullChecker.isNullish(path)) {
			mergedUri = null;
		} else {
			mergedUri = UriBuilder.fromUri(uri).path(path).build();
		}
		return mergedUri;
	}

	public static URI appendQueryString(URI uri, String paramName) {
		return appendQueryString(uri, paramName, "");
	}

	public static URI appendQueryString(URI uri, String paramName, Object paramValue) {
		URI mergedUri = null;
		if (uri == null) {
			mergedUri = null;
		} else if (NullChecker.isNullish(paramName)) {
			mergedUri = uri;
		} else {
			mergedUri = UriBuilder.fromUri(uri).queryParam(paramName, paramValue).build();
		}
		return mergedUri;
	}

	public static URI setQueryString(URI uri, String paramName, Object paramValue) {
		URI mergedUri = null;
		if (uri == null) {
			mergedUri = null;
		} else if (NullChecker.isNullish(paramName)) {
			mergedUri = uri;
		} else {
			mergedUri = UriBuilder.fromUri(uri).replaceQueryParam(paramName, paramValue).build();
		}
		return mergedUri;
	}

	public static URI createUri(String uri) {
		return UriBuilder.fromUri(uri).build();
	}

}