package com.foxx.androidcast.discovery;

/*********************************************************************
 * DiscoverySelfFilter.java
 * Created at: Sun 17 May 2026 15:45:19 +0200
 * Updated at: Wed 20 May 2026 15:17:13 +0200 by Anton Afanasyeu <a.afanasieff@gmail.com>
 * Commit: 5d8e82d2e60a21fff3138d2a394ee4e8b4c6dcb8
 * Contributors:
 *    - Anton Afanasyeu <a.afanasieff@gmail.com> (2 commits, 73 lines)
 *    - Cursor Agent (project assistant)
 * Digest: SHA256	cf0c0de407834543412ba5d8f3b89feb1f44a4f7a4258de315aed83a7a0436df
**********************************************************************/
import android.content.Context;

import com.foxx.androidcast.DeviceInfo;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;

/** Drops LAN discovery entries that refer to this device. */
final class DiscoverySelfFilter {
    private DiscoverySelfFilter() {}

    static boolean isSelf(Context context, String host, String remoteDeviceUuid) {
        if (context != null && remoteDeviceUuid != null && !remoteDeviceUuid.isEmpty()) {
            if (remoteDeviceUuid.equals(DeviceInfo.getDeviceUuid(context.getApplicationContext()))) {
                return true;
            }
        }
        return isLocalHost(host);
    }

    static boolean isLocalHost(String host) {
        if (host == null || host.isEmpty()) {
            return false;
        }
        if ("127.0.0.1".equals(host) || "::1".equals(host) || "0:0:0:0:0:0:0:1".equals(host)) {
            return true;
        }
        for (String local : localIpv4Addresses()) {
            if (local.equals(host)) {
                return true;
            }
        }
        return false;
    }

    private static Set<String> localIpv4Addresses() {
        Set<String> out = new HashSet<>();
        try {
            Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces();
            if (ifaces == null) {
                return out;
            }
            for (NetworkInterface ni : Collections.list(ifaces)) {
                if (!ni.isUp() || ni.isLoopback()) {
                    continue;
                }
                for (InetAddress addr : Collections.list(ni.getInetAddresses())) {
                    if (addr instanceof Inet4Address && !addr.isLoopbackAddress()) {
                        String h = addr.getHostAddress();
                        if (h != null) {
                            out.add(h);
                        }
                    }
                }
            }
        } catch (Exception ignored) {
        }
        return out;
    }
}
