/*
 * Copyright 2008-2026 Async-IO.org
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package org.atmosphere.websocket.protocol;

import org.atmosphere.cpr.AtmosphereResourceImpl;
import org.atmosphere.cpr.Broadcaster;
import org.atmosphere.websocket.WebSocket;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

class EchoProtocolTest {

    private WebSocket webSocket;
    private AtmosphereResourceImpl resource;
    private Broadcaster broadcaster;
    private EchoProtocol protocol;

    @BeforeEach
    void setUp() {
        webSocket = mock(WebSocket.class);
        resource = mock(AtmosphereResourceImpl.class);
        broadcaster = mock(Broadcaster.class);
        protocol = new EchoProtocol();
    }

    @Test
    void onMessageStringBroadcasts() {
        when(webSocket.resource()).thenReturn(resource);
        when(resource.getBroadcaster()).thenReturn(broadcaster);

        var result = protocol.onMessage(webSocket, "hello");

        verify(broadcaster).broadcast("hello");
        assertNull(result);
    }

    @Test
    void onMessageBytesBroadcastsCopy() {
        when(webSocket.resource()).thenReturn(resource);
        when(resource.getBroadcaster()).thenReturn(broadcaster);

        byte[] data = "hello world".getBytes();
        var result = protocol.onMessage(webSocket, data, 6, 5);

        verify(broadcaster).broadcast("world".getBytes());
        assertNull(result);
    }

    @Test
    void onMessageBytesFullArray() {
        when(webSocket.resource()).thenReturn(resource);
        when(resource.getBroadcaster()).thenReturn(broadcaster);

        byte[] data = {1, 2, 3};
        protocol.onMessage(webSocket, data, 0, 3);

        verify(broadcaster).broadcast(data);
    }

    @Test
    void configureDoesNotThrow() {
        protocol.configure(null);
    }

    @Test
    void onOpenDoesNotThrow() {
        protocol.onOpen(webSocket);
    }

    @Test
    void onCloseDoesNotThrow() {
        protocol.onClose(webSocket);
    }
}
