/*
 * 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 com.google.dataflow.sample.timeseriesflow.transforms;

import com.google.dataflow.sample.timeseriesflow.TimeSeriesData.TSAccum;
import com.google.dataflow.sample.timeseriesflow.TimeSeriesData.TSAccumSequence;
import com.google.dataflow.sample.timeseriesflow.TimeSeriesData.TSKey;
import org.apache.beam.sdk.transforms.DoFn;
import org.apache.beam.sdk.transforms.GroupByKey;
import org.apache.beam.sdk.transforms.PTransform;
import org.apache.beam.sdk.transforms.ParDo;
import org.apache.beam.sdk.transforms.Reify;
import org.apache.beam.sdk.transforms.Values;
import org.apache.beam.sdk.transforms.windowing.DefaultTrigger;
import org.apache.beam.sdk.transforms.windowing.GlobalWindows;
import org.apache.beam.sdk.values.KV;
import org.apache.beam.sdk.values.PCollection;
import org.apache.beam.sdk.values.PCollection.IsBounded;
import org.apache.beam.sdk.values.ValueInSingleWindow;
import org.apache.beam.sdk.values.WindowingStrategy;

/**
 * Given a set of TSKey's, generate a PCollection of KV where all {@link TSKey#getMajorKey()} within
 * a window context are collapsed together. The Iterable, which is normally a {@link
 * TSAccumSequence} or {@link TSAccum} will be a 'snapshot' of all time series for that window.
 *
 * <p>This is done by: 1- Change the TSKey in the KV to have major key == the window context 2- GBK
 */
public class GenerateMajorKeyWindowSnapshot {

  public static <T> CollapseKeysToWindowContext<T> generateWindowSnapshot() {
    return new CollapseKeysToWindowContext<>();
  }

  private static class CollapseKeysToWindowContext<T>
      extends PTransform<PCollection<KV<TSKey, T>>, PCollection<Iterable<T>>> {

    @Override
    public PCollection<Iterable<T>> expand(PCollection<KV<TSKey, T>> input) {

      WindowingStrategy<?, ?> windowingStrategy = input.getWindowingStrategy();
      if (windowingStrategy.getWindowFn() instanceof GlobalWindows
          && windowingStrategy.getTrigger() instanceof DefaultTrigger
          && input.isBounded() != IsBounded.BOUNDED) {
        throw new IllegalStateException(
            "CollapseTSMinorKeys cannot be applied to non-bounded PCollection in the GlobalWindow without a trigger. Use a Window.into or Window.triggering transform prior to CollapseTSMinorKeys.");
      }

      return input
          .apply(new CollapseToWindowMajorKey<>())
          .apply(GroupByKey.create())
          .apply(Values.create());
    }
  }

  /** Given a KV<TSKey,T> set the TSKey to window context. */
  private static class CollapseToWindowMajorKey<T>
      extends PTransform<PCollection<KV<TSKey, T>>, PCollection<KV<TSKey, T>>> {

    @Override
    public PCollection<KV<TSKey, T>> expand(PCollection<KV<TSKey, T>> input) {
      return input.apply(Reify.windowsInValue()).apply(ParDo.of(new ReplaceMajorKeyWithWindow<>()));
    }
  }

  private static class ReplaceMajorKeyWithWindow<T>
      extends DoFn<KV<TSKey, ValueInSingleWindow<T>>, KV<TSKey, T>> {
    @ProcessElement
    public void process(
        @Element KV<TSKey, ValueInSingleWindow<T>> input, OutputReceiver<KV<TSKey, T>> o) {
      o.output(
          KV.of(
              input
                  .getKey()
                  .toBuilder()
                  .setMajorKey(input.getValue().getWindow().toString())
                  .build(),
              input.getValue().getValue()));
    }
  }

  private static class ReplaceMinorKeyWithWindow<T>
      extends DoFn<KV<TSKey, ValueInSingleWindow<T>>, KV<TSKey, T>> {
    @ProcessElement
    public void process(
        @Element KV<TSKey, ValueInSingleWindow<T>> input, OutputReceiver<KV<TSKey, T>> o) {
      o.output(
          KV.of(
              input
                  .getKey()
                  .toBuilder()
                  .setMinorKeyString(input.getValue().getWindow().toString())
                  .build(),
              input.getValue().getValue()));
    }
  }
}

@@ -3117,29 +3117,24 @@
 apseToWindow
-Major
 Key%3C%3E())%0A   
@@ -3315,21 +3315,16 @@
 ToWindow
-Major
 Key%3CT%3E%0A 
@@ -3564,37 +3564,32 @@
 o.of(new Replace
-Major
 KeyWithWindow%3C%3E(
@@ -3638,540 +3638,8 @@
 lace
-MajorKeyWithWindow%3CT%3E%0A      extends DoFn%3CKV%3CTSKey, ValueInSingleWindow%3CT%3E%3E, KV%3CTSKey, T%3E%3E %7B%0A    @ProcessElement%0A    public void process(%0A        @Element KV%3CTSKey, ValueInSingleWindow%3CT%3E%3E input, OutputReceiver%3CKV%3CTSKey, T%3E%3E o) %7B%0A      o.output(%0A          KV.of(%0A              input%0A                  .getKey()%0A                  .toBuilder()%0A                  .setMajorKey(input.getValue().getWindow().toString())%0A                  .build(),%0A              input.getValue().getValue()));%0A    %7D%0A  %7D%0A%0A  private static class ReplaceMinor
 KeyW
@@ -3909,109 +3909,38 @@
     
-input%0A                  .getKey()%0A                  .toBuilder()%0A                  
+TSKey.newBuilder()
 .setM
-in
+aj
 orKey
-String
 (inp
@@ -3980,27 +3980,8 @@
 g())
-%0A                  
 .bui

Fix issue with Snapshot + Multivariate not collapsing all values