package dev.fyloz.trial.colorrecipesexplorer.utils;

import dev.fyloz.trial.colorrecipesexplorer.config.Preferences;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.net.URI;
import java.net.URISyntaxException;

public class ControllerUtils {

    private static final String HTTP_SCHEME = "http";
    private static final String HTTPS_SCHEME = "https";

    public static String redirect(String viewName) {
        return String.format("redirect:/%s", viewName);
    }

    public static URI getUri(HttpServletRequest request) throws URISyntaxException {
        return new URI(request.getRequestURL().toString());
    }

    public static String getUrlFromURI(URI uri) {
        String host = uri.getHost();
        int port = uri.getPort();
        String scheme = getScheme();

        return String.format("%s://%s:%s", scheme, host, port);
    }

    public static String getCurrentBaseUrl() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) return "";

        HttpServletRequest request = attributes.getRequest();

        String port = ":" + (Preferences.urlUsePort ? request.getServerPort() : "");
        return String.format("%s://%s%s%s", getScheme(), request.getServerName(), port, request.getContextPath());
    }

    public static String getLatestUrl() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) return "";

        HttpServletRequest request = attributes.getRequest();

        try {
            String currentDomainName = getUrlFromURI(getUri(request));
            String referer = request.getHeader("referer");
            if (referer == null) return currentDomainName;

            String refererURL = getUrlFromURI(new URI(referer));

            return refererURL.equals(currentDomainName) ? referer : currentDomainName;
        } catch (URISyntaxException e) {
            return "";
        }
    }

    private static String getScheme() {
        return Preferences.urlUseHttps ? HTTPS_SCHEME : HTTP_SCHEME;
    }
}
