package com.foxx.androidcast.remoteaccess.control;

import android.text.TextUtils;

import java.util.Locale;
import java.util.Map;

/** Bearer / query-token checks for the RA control HTTP server. */
public final class RemoteAccessControlAuth {
    public static final String HEADER = "Authorization";
    public static final String QUERY_PARAM = "token";

    private RemoteAccessControlAuth() {}

    public static boolean isAuthorized(String expectedToken, String authorizationHeader, String queryToken) {
        if (TextUtils.isEmpty(expectedToken)) {
            return false;
        }
        if (!TextUtils.isEmpty(queryToken) && expectedToken.equals(queryToken.trim())) {
            return true;
        }
        if (TextUtils.isEmpty(authorizationHeader)) {
            return false;
        }
        String header = authorizationHeader.trim();
        if (header.regionMatches(true, 0, "Bearer ", 0, 7)) {
            return expectedToken.equals(header.substring(7).trim());
        }
        return expectedToken.equals(header);
    }

    public static String bearerHeader(String token) {
        return "Bearer " + (token != null ? token : "");
    }

    public static String extractQueryToken(String path, Map<String, String> query) {
        if (query != null && query.containsKey(QUERY_PARAM)) {
            return query.get(QUERY_PARAM);
        }
        if (path == null) {
            return "";
        }
        int q = path.indexOf('?');
        if (q < 0) {
            return "";
        }
        String qs = path.substring(q + 1);
        for (String pair : qs.split("&")) {
            int eq = pair.indexOf('=');
            if (eq <= 0) {
                continue;
            }
            String key = pair.substring(0, eq);
            if (QUERY_PARAM.equals(key)) {
                return pair.substring(eq + 1);
            }
        }
        return "";
    }

    public static String normalizePath(String path) {
        if (path == null || path.isEmpty()) {
            return "/";
        }
        int q = path.indexOf('?');
        if (q >= 0) {
            path = path.substring(0, q);
        }
        if (!path.startsWith("/")) {
            path = "/" + path;
        }
        return path.toLowerCase(Locale.US);
    }
}
