/*
 * 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.iotdb.pipe.api.event;

/**
 * User defined event is used to wrap data generated by users, keeping a source event to
 * automatically report the processing progress to pipe engine.
 */
public abstract class UserDefinedEvent implements Event {

  /** The user defined event is generated from this source event. */
  protected final Event sourceEvent;

  /**
   * @param sourceEvent The source event of this user defined event which is used to report the
   *     processing progress to pipe engine. Please notice that the source event should satisfy the
   *     following conditions: 1. A source event can only be assigned to one user defined event. 2.
   *     If more than one user defined events are generated from the same source event, only the
   *     last generated user defined event can be assigned with the source event, others should be
   *     assigned {@code null}, or call {@link #UserDefinedEvent()} to generate a user defined event
   *     without source event.
   */
  protected UserDefinedEvent(Event sourceEvent) {
    this.sourceEvent = parseRootSourceEvent(sourceEvent);
  }

  /** Generate a user defined event without source event. */
  protected UserDefinedEvent() {
    this.sourceEvent = null;
  }

  private Event parseRootSourceEvent(Event sourceEvent) {
    return sourceEvent instanceof UserDefinedEvent
        ? ((UserDefinedEvent) sourceEvent).getSourceEvent()
        : sourceEvent;
  }

  public Event getSourceEvent() {
    return sourceEvent;
  }
}
