/*
 * Copyright (C) 2026  Tim Zimmermann <tim@aglais.org>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.aglais.zms.server;

import io.netty.channel.Channel;
import io.netty.handler.codec.http2.Http2StreamChannel;
import io.netty.handler.codec.quic.QuicChannel;
import io.netty.handler.codec.quic.QuicStreamChannel;

import java.net.SocketAddress;

/**
 * Helper class for interacting with {@link Channel}s
 */
public class ChannelUtil {

    /**
     * Check if this {@link Channel} is the child of a connection channel
     * This currently is the case with {@link Http2StreamChannel} and {@link QuicStreamChannel}
     *
     * @param ch The channel to check
     * @return True if the channel is a child connection, false otherwise
     */
    public static boolean isChildConnectionChannel(Channel ch) {
        return ch instanceof Http2StreamChannel || ch instanceof QuicStreamChannel;
    }

    /**
     * Get a {@link Channel}'s remote address, taking care of special cases (HTTP/3)
     *
     * @param ch The channel to get the remote address of
     * @return The channel's remote {@link SocketAddress}
     */
    public static SocketAddress getRemoteAddress(Channel ch) {
        if (ch instanceof QuicStreamChannel)
            return ((QuicChannel) ch.parent()).remoteSocketAddress();

        return ch.remoteAddress();
    }

    /**
     * Get a {@link Channel}'s local address, taking care of special cases (HTTP/3)
     *
     * @param ch The channel to get the local address of
     * @return The channel's local {@link SocketAddress}
     */
    public static SocketAddress getLocalAddress(Channel ch) {
        if (ch instanceof QuicStreamChannel)
            return ((QuicChannel) ch.parent()).localSocketAddress();

        return ch.localAddress();
    }

}
