/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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.postgresql.test.jdbc4;

import org.postgresql.PGConnection;
import org.postgresql.copy.CopyManager;
import org.postgresql.test.TestUtil;
import org.postgresql.test.jdbc2.BaseTest4;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.rmi.ServerException;
import java.sql.ResultSet;
import java.sql.SQLException;

public class CopyUtfTest extends BaseTest4 {
  @Override
  @Before
  public void setUp() throws Exception {
    super.setUp();
    TestUtil.createTable(con, "testtable", "text1 character varying, text2 character varying,text3 character varying");
  }

  @Override
  @After
  public void tearDown() throws SQLException {
    super.tearDown();
  }

  @Test
  public void copyTest() throws Exception {
    PGConnection pgcon = con.unwrap(PGConnection.class);
    CopyManager mgr = pgcon.getCopyAPI();
    try {

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try (OutputStreamWriter wr = new OutputStreamWriter(baos, StandardCharsets.UTF_8)) {
      // Write 10 rows
      for (int i = 0; i < 10; i++) {
        wr.write("INR,字仮名交じり文,3255104BTK1\n");
      }
    }

    try (InputStream fis = new FileInputStream("file.csv")) {
      mgr.copyIn(sql, fis);
    }

    String sql = "COPY testtable  FROM stdin delimiter ','  NULL AS 'null' ENCODING 'UTF8'";
    mgr.copyIn(sql, new ByteArrayInputStream(baos.toByteArray()));
      ResultSet rs = con.createStatement().executeQuery("select count(*) from testtable");
      rs.next();
      System.out.println("rs.getInt(1) = " + rs.getInt(1));


    } catch (SQLException ex) {
      throw new ServerException("Error while copying data in Postgres DB:", ex);
    }
  }
}
