package com.onsemi.middleware.UECommon.model.db;

import java.util.function.Function;
import java.util.stream.Stream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.util.UriComponentsBuilder;

import com.svetylkovo.rojo.Rojo;

public class DbUrlParser {

	protected Logger logger = LoggerFactory.getLogger(this.getClass());

	private String url;

	public DbUrlParser(String url) {
		this.url = url.toUpperCase();
	}

	public String getSidSchemaDbNameFromUrl() throws Exception {
		Stream<String> database = Rojo.firstGroup(";DATABASE=([^;]+)", url);
		Stream<String> databaseName = Rojo.firstGroup(";DATABASENAME=([^;]+)", url);
		Stream<String> instance = Rojo.firstGroup(";INSTANCE=([^;]+)", url);
		Stream<String> instanceName = Rojo.firstGroup(";INSTANCENAME=([^;]+)", url);
		Stream<String> db = Rojo.firstGroup("DB=([^&]+)", url);

		Stream<String> serviceName = Rojo.firstGroup("\\(SERVICE_NAME=(.+?)\\)", url);
		Stream<String> doubleSlash = Rojo.firstGroup(":\\/\\/([^\\.]+)", url);

		return Stream.of(database, databaseName, instance, instanceName, db, serviceName, doubleSlash)
					 .flatMap(Function.identity())
					 .findFirst()
					 .orElseGet(() -> {
						 try {
							 String parseForHost = getUrl();
							 parseForHost = parseForHost.replaceAll("JDBC:[A-z]+:", "JDBC:");
							 if (!parseForHost.contains("://")) {
								 parseForHost = parseForHost.replaceFirst(":", "://");
							 }
							 return UriComponentsBuilder.fromUriString(parseForHost)
														.build()
														.getHost();
						 } catch (Exception e){
							 logger.error("Could not parse URL {} - not even to obtain a hostname", getUrl(), e);
							 return "PARSING-ERROR";
						 }

					 });
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url.toLowerCase();
	}

}
