package invalid.lena.scrcpy;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class DevicesTest {

    @Test
    public void parseEmptyOrNull() {
        assertTrue(Devices.parse(null).isEmpty());
        assertTrue(Devices.parse("").isEmpty());
        assertTrue(Devices.parse("   ").isEmpty());
    }

    @Test
    public void parseNonArrayReturnsEmpty() {
        assertTrue(Devices.parse("{not json").isEmpty());
        assertTrue(Devices.parse("{\"host\":\"x\"}").isEmpty());
    }

    @Test
    public void parseSkipsMalformedRowsKeepsValid() {
        // Middle row missing 'port' - must NOT nuke the other two.
        String json = "["
                + "{\"host\":\"a\",\"port\":1},"
                + "{\"host\":\"bad\"},"
                + "{\"host\":\"c\",\"port\":3}"
                + "]";
        List<Devices.Device> got = Devices.parse(json);
        assertEquals(2, got.size());
        assertEquals("a", got.get(0).host);
        assertEquals("c", got.get(1).host);
    }

    @Test
    public void roundTrip() {
        List<Devices.Device> in = new ArrayList<>(Arrays.asList(
                new Devices.Device("192.168.1.10", 5555),
                new Devices.Device("10.0.0.2",     43210)));
        String json = Devices.serialize(in);
        List<Devices.Device> out = Devices.parse(json);
        assertEquals(2, out.size());
        assertEquals("192.168.1.10", out.get(0).host);
        assertEquals(5555,           out.get(0).port);
        assertEquals("10.0.0.2",     out.get(1).host);
        assertEquals(43210,          out.get(1).port);
    }

    @Test
    public void deviceEqualsByHostAndPort() {
        Devices.Device a = new Devices.Device("1.1.1.1", 5555);
        Devices.Device b = new Devices.Device("1.1.1.1", 5555);
        Devices.Device c = new Devices.Device("1.1.1.1", 5556);
        assertEquals(a, b);
        assertEquals(a.hashCode(), b.hashCode());
        assertEquals(false, a.equals(c));
    }
}
