/*
 * Copyright (c) 2004, PostgreSQL Global Development Group
 * See the LICENSE file in the project root for more information.
 */

package org.postgresql.test.jdbc2;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;

import org.postgresql.core.Encoding;

import org.junit.jupiter.api.Test;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.Reader;
import java.util.Locale;

/**
 * Tests for the Encoding class.
 */
class EncodingTest {

  @Test
  void creation() throws Exception {
    Encoding encoding = Encoding.getDatabaseEncoding("UTF8");
    assertEquals("UTF", encoding.name().substring(0, 3).toUpperCase(Locale.US));
    encoding = Encoding.getDatabaseEncoding("SQL_ASCII");
    assertTrue(encoding.name().toUpperCase(Locale.US).contains("ASCII"));
    assertEquals(Encoding.defaultEncoding(), Encoding.getDatabaseEncoding("UNKNOWN"), "When encoding is unknown the default encoding should be used");
  }

  @Test
  void transformations() throws Exception {
    Encoding encoding = Encoding.getDatabaseEncoding("UTF8");
    assertEquals("ab", encoding.decode(new byte[]{97, 98}));

    assertEquals(2, encoding.encode("ab").length);
    assertEquals(97, encoding.encode("a")[0]);
    assertEquals(98, encoding.encode("b")[0]);

    encoding = Encoding.defaultEncoding();
    assertEquals("a".getBytes()[0], encoding.encode("a")[0]);
    assertEquals(new String(new byte[]{97}), encoding.decode(new byte[]{97}));
  }

  @Test
  void reader() throws Exception {
    Encoding encoding = Encoding.getDatabaseEncoding("SQL_ASCII");
    InputStream stream = new ByteArrayInputStream(new byte[]{97, 98});
    Reader reader = encoding.getDecodingReader(stream);
    assertEquals(97, reader.read());
    assertEquals(98, reader.read());
    assertEquals(-1, reader.read());
  }
}
