/*
 * 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.druid.timeline.partition;

import com.google.common.base.Preconditions;
import org.apache.druid.java.util.common.IAE;
import org.apache.druid.java.util.common.ISE;
import org.apache.druid.timeline.Overshadowable;

import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * A set of {@link PartitionChunk}s which should be atomically visible or not in the timeline.
 * This is usually a set of single partitionChunk for first-generation segments.
 * For non-first-generation segments generated by overwriting tasks, segments of the same interval generated by
 * the same task become an atomicUpdateGroup. As a result, all segments in an atomicUpdateGroup have the same
 * rootPartitionp range, majorVersion, minorVersion, and atomicUpdateGroupSize.
 */
class AtomicUpdateGroup<T extends Overshadowable<T>> implements Overshadowable<AtomicUpdateGroup<T>>
{
  // Perhaps it would be worth to store these in a map of (partitionId -> partitionChunk)
  // because sometimes we need to search for a particular partitionChunk corresponding to a partitionId.
  // However, there's a tradeoff between time and space. Storing in a map would be faster than storing in a list,
  // but it would take at least additional 4 bytes per chunk to store its key.
  // This may matter if there are a lot of segments to keep in memory as in brokers or the coordinator.
  private final List<PartitionChunk<T>> chunks = new ArrayList<>();

  static <T extends Overshadowable<T>> AtomicUpdateGroup<T> copy(AtomicUpdateGroup<T> group)
  {
    return new AtomicUpdateGroup<>(group.chunks);
  }

  AtomicUpdateGroup(PartitionChunk<T> chunk)
  {
    this.chunks.add(chunk);
  }

  private AtomicUpdateGroup(List<PartitionChunk<T>> chunks)
  {
    this.chunks.addAll(chunks);
  }

  public void add(PartitionChunk<T> chunk)
  {
    if (isFull()) {
      throw new IAE("Can't add more chunk[%s] to atomicUpdateGroup[%s]", chunk, chunks);
    }
    if (!isEmpty() && !isSameAtomicUpdateGroup(chunks.get(0), chunk)) {
      throw new IAE("Can't add chunk[%s] to a different atomicUpdateGroup[%s]", chunk, chunks);
    }
    for (PartitionChunk<T> existing : chunks) {
      if (existing.equals(chunk)) {
        throw new ISE("Can't add same chunk[%s] again", chunk);
      }
    }
    chunks.add(chunk);
  }

  public void remove(PartitionChunk<T> chunk)
  {
    if (chunks.isEmpty()) {
      throw new ISE("Can't remove chunk[%s] from empty atomicUpdateGroup", chunk);
    }

    if (!isSameAtomicUpdateGroup(chunks.get(0), chunk)) {
      throw new IAE("Can't remove chunk[%s] from a different atomicUpdateGroup[%s]", chunk, chunks);
    }

    chunks.remove(chunk);
  }

  public boolean isFull()
  {
    return !isEmpty() && chunks.size() == chunks.get(0).getObject().getAtomicUpdateGroupSize();
  }

  public boolean isEmpty()
  {
    return chunks.isEmpty();
  }

  public List<PartitionChunk<T>> getChunks()
  {
    return chunks;
  }

  @Nullable
  PartitionChunk<T> findChunk(int partitionId)
  {
    return chunks.stream().filter(chunk -> chunk.getChunkNumber() == partitionId).findFirst().orElse(null);
  }

  @Override
  public int getStartRootPartitionId()
  {
    Preconditions.checkState(!isEmpty(), "Empty atomicUpdateGroup");
    return chunks.get(0).getObject().getStartRootPartitionId();
  }

  @Override
  public int getEndRootPartitionId()
  {
    Preconditions.checkState(!isEmpty(), "Empty atomicUpdateGroup");
    return chunks.get(0).getObject().getEndRootPartitionId();
  }

  @Override
  public String getVersion()
  {
    Preconditions.checkState(!isEmpty(), "Empty atomicUpdateGroup");
    return chunks.get(0).getObject().getVersion();
  }

  @Override
  public short getMinorVersion()
  {
    Preconditions.checkState(!isEmpty(), "Empty atomicUpdateGroup");
    return chunks.get(0).getObject().getMinorVersion();
  }

  @Override
  public short getAtomicUpdateGroupSize()
  {
    Preconditions.checkState(!isEmpty(), "Empty atomicUpdateGroup");
    return chunks.get(0).getObject().getAtomicUpdateGroupSize();
  }

  @Override
  public boolean equals(Object o)
  {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    AtomicUpdateGroup<?> that = (AtomicUpdateGroup<?>) o;
    return Objects.equals(chunks, that.chunks);
  }

  @Override
  public int hashCode()
  {
    return Objects.hash(chunks);
  }

  @Override
  public String toString()
  {
    return "AtomicUpdateGroup{" +
           "chunks=" + chunks +
           '}';
  }

  private static <T extends Overshadowable<T>> boolean isSameAtomicUpdateGroup(
      PartitionChunk<T> c1,
      PartitionChunk<T> c2
  )
  {
    return c1.getObject().getStartRootPartitionId() == c2.getObject().getStartRootPartitionId()
        && c1.getObject().getEndRootPartitionId() == c2.getObject().getEndRootPartitionId()
        && c1.getObject().getMinorVersion() == c2.getObject().getMinorVersion()
        && c1.getObject().getAtomicUpdateGroupSize() == c2.getObject().getAtomicUpdateGroupSize();
  }
}
