/*
 * 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.apache.beam.sdk.io.gcp.bigquery;

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

import com.google.api.services.bigquery.model.QueryResponse;
import com.google.api.services.bigquery.model.TableFieldSchema;
import com.google.api.services.bigquery.model.TableRow;
import com.google.api.services.bigquery.model.TableSchema;
import com.google.common.collect.ImmutableList;
import java.io.IOException;
import org.apache.beam.sdk.Pipeline;
import org.apache.beam.sdk.extensions.gcp.options.GcpOptions;
import org.apache.beam.sdk.io.GenerateSequence;
import org.apache.beam.sdk.io.gcp.testing.BigqueryClient;
import org.apache.beam.sdk.options.PipelineOptionsFactory;
import org.apache.beam.sdk.testing.TestPipeline;
import org.apache.beam.sdk.transforms.DoFn;
import org.apache.beam.sdk.transforms.ParDo;
import org.apache.beam.sdk.transforms.SerializableFunction;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/**
 * Integration tests for {@link
 * org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO#write(SerializableFunction)}. This test writes
 * 30MB data to BQ and verify the written row count.
 */
@RunWith(JUnit4.class)
public class BigQueryIOStorageWriteIT {

  private enum WriteMode {
    EXACT_ONCE,
    AT_LEAST_ONCE
  };

  private String project;
  private static final String DATASET_ID = "big_query_storage";
  private static final String TABLE_PREFIX = "storage_write_";

  private BigQueryOptions bqOptions;
  private static final BigqueryClient BQ_CLIENT = new BigqueryClient("BigQueryStorageIOWriteIT");

  private void setUpTestEnvironment(WriteMode writeMode) {
    PipelineOptionsFactory.register(BigQueryOptions.class);
    bqOptions = TestPipeline.testingPipelineOptions().as(BigQueryOptions.class);
    bqOptions.setProject(TestPipeline.testingPipelineOptions().as(GcpOptions.class).getProject());
    if (writeMode == WriteMode.EXACT_ONCE) {
      bqOptions.setUseStorageWriteApi(true);
    } else {
      bqOptions.setUseStorageWriteApiAtLeastOnce(true);
    }
    bqOptions.setNumStorageWriteApiStreams(2);
    bqOptions.setStorageWriteApiTriggeringFrequencySec(1);
    project = TestPipeline.testingPipelineOptions().as(GcpOptions.class).getProject();
  }

  private void runBigQueryIOStorageWritePipeline(int rowCount, WriteMode writeMode) {
    String tableName = TABLE_PREFIX + System.currentTimeMillis();
    TableSchema schema =
        new TableSchema()
            .setFields(
                ImmutableList.of(
                    new TableFieldSchema().setName("number").setType("INTEGER"),
                    new TableFieldSchema().setName("str").setType("STRING")));

    Pipeline p = Pipeline.create(bqOptions);
    p.apply("Input", GenerateSequence.from(0).to(rowCount))
        .apply(
            "GenerateMessage",
            ParDo.of(
                new DoFn<Long, TableRow>() {
                  @ProcessElement
                  public void processElement(ProcessContext c) {
                    c.output(new TableRow().set("number", c.element()).set("str", "aaaaaaaaaa"));
                  }
                }))
        .apply(
            "WriteToBQ",
            BigQueryIO.writeTableRows()
                .to(String.format("%s:%s.%s", project, DATASET_ID, tableName))
                .withSchema(schema)
                .withCreateDisposition(BigQueryIO.Write.CreateDisposition.CREATE_IF_NEEDED)
                .withWriteDisposition(BigQueryIO.Write.WriteDisposition.WRITE_APPEND));
    p.run().waitUntilFinish();
    String testQuery = String.format("SELECT count(*) FROM [%s.%s];", DATASET_ID, tableName);
    try {
      QueryResponse response = BQ_CLIENT.queryWithRetries(testQuery, project);
      if (writeMode == WriteMode.EXACT_ONCE) {
        assertEquals((int) response.getRows().get(0).getF().get(0).getV(), rowCount);
      } else {
        assertTrue((int) response.getRows().get(0).getF().get(0).getV() >= rowCount);
      }
    } catch (IOException e) {
      assertTrue("Unexpected exception: " + e.toString(), false);
    } catch (InterruptedException e) {
      assertTrue("Unexpected exception: " + e.toString(), false);
    }
  }

  @Test
  public void testBigQueryStorageWrite30MProto() throws Exception {
    setUpTestEnvironment(WriteMode.EXACT_ONCE);
    runBigQueryIOStorageWritePipeline(3000000, WriteMode.EXACT_ONCE);
  }

  @Test
  public void testBigQueryStorageWrite30MProtoALO() throws Exception {
    setUpTestEnvironment(WriteMode.AT_LEAST_ONCE);
    runBigQueryIOStorageWritePipeline(3000000, WriteMode.AT_LEAST_ONCE);
  }
}

@@ -3075,16 +3075,238 @@
 );%0A  %7D%0A%0A
+  static class FillRowFn extends DoFn%3CLong, TableRow%3E %7B%0A    @ProcessElement%0A    public void processElement(ProcessContext c) %7B%0A      c.output(new TableRow().set(%22number%22, c.element()).set(%22str%22, %22aaaaaaaaaa%22));%0A    %7D%0A  %7D%0A%0A
   privat
@@ -3839,29 +3839,16 @@
  .apply(
-%0A            
 %22Generat
@@ -3861,310 +3861,33 @@
 ge%22,
-%0A            ParDo.of(%0A                new DoFn%3CLong, TableRow%3E() %7B%0A                  @ProcessElement%0A                  public void processElement(ProcessContext c) %7B%0A                    c.output(new TableRow().set(%22number%22, c.element()).set(%22str%22, %22aaaaaaaaaa%22));%0A                  %7D%0A                %7D
+ ParDo.of(new FillRowFn()
 ))%0A 

make DoFn into a separate class