package com.njcn.gather.device.util;

import org.junit.Test;

import javax.imageio.ImageIO;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

public class PqDevImageSupportTest {

    @Test
    public void buildEchoPayloadReturnsEmptyFieldsWhenImageMissing() {
        PqDevImageSupport.ImageEchoPayload payload = PqDevImageSupport.buildEchoPayload(null);

        assertFalse(payload.isHasImage());
        assertNull(payload.getImageBase64());
        assertNull(payload.getImageContentType());
    }

    @Test
    public void buildEchoPayloadDetectsPngAndCreatesBase64() throws Exception {
        byte[] imageBytes = createImageBytes("png");

        PqDevImageSupport.ImageEchoPayload payload = PqDevImageSupport.buildEchoPayload(imageBytes);

        assertTrue(payload.isHasImage());
        assertEquals("image/png", payload.getImageContentType());
        assertNotNull(payload.getImageBase64());
        assertFalse(payload.getImageBase64().isEmpty());
    }

    @Test(expected = IllegalArgumentException.class)
    public void detectContentTypeRejectsInvalidImageBytes() {
        PqDevImageSupport.detectContentType(new byte[]{1, 2, 3, 4});
    }

    private byte[] createImageBytes(String format) throws Exception {
        BufferedImage image = new BufferedImage(2, 2, BufferedImage.TYPE_INT_RGB);
        image.setRGB(0, 0, Color.RED.getRGB());
        image.setRGB(1, 0, Color.GREEN.getRGB());
        image.setRGB(0, 1, Color.BLUE.getRGB());
        image.setRGB(1, 1, Color.WHITE.getRGB());

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, format, outputStream);
        return outputStream.toByteArray();
    }
}
