/*
 * Copyright 2015 the original author or authors.
 *
 * Licensed 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 net.kuujo.copycat.collections.state;

import net.kuujo.copycat.PersistenceLevel;
import net.kuujo.copycat.raft.Session;
import net.kuujo.copycat.raft.server.Apply;
import net.kuujo.copycat.raft.server.Commit;
import net.kuujo.copycat.raft.server.StateMachine;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * Distributed set state machine.
 *
 * @author <a href="http://github.com/kuujo">Jordan Halterman</a>
 */
public class SetState extends StateMachine {
  private Map<Integer, Commit<? extends SetCommands.TtlCommand>> map;
  private final Set<Long> sessions = new HashSet<>();

  @Override
  public void register(Session session) {
    sessions.add(session.id());
  }

  @Override
  public void expire(Session session) {
    sessions.remove(session.id());
  }

  @Override
  public void close(Session session) {
    sessions.remove(session.id());
  }

  /**
   * Returns a boolean value indicating whether the given commit is active.
   */
  private boolean isActive(Commit<? extends SetCommands.TtlCommand> commit, long time) {
    if (commit == null) {
      return false;
    } else if (commit.operation().mode() == PersistenceLevel.EPHEMERAL && !sessions.contains(commit.session().id())) {
      return false;
    } else if (commit.operation().ttl() != 0 && commit.operation().ttl() < time - commit.timestamp()) {
      return false;
    }
    return true;
  }

  /**
   * Handles a contains commit.
   */
  @Apply(SetCommands.Contains.class)
  protected boolean contains(Commit<SetCommands.Contains> commit) {
    try {
      if (map == null) {
        return false;
      }

      Commit<? extends SetCommands.TtlCommand> command = map.get(commit.operation().value());
      if (!isActive(command, commit.timestamp())) {
        map.remove(commit.operation().value());
        return false;
      }
      return true;
    } finally {
      commit.close();
    }
  }

  /**
   * Handles an add commit.
   */
  @Apply(SetCommands.Add.class)
  protected boolean add(Commit<SetCommands.Add> commit) {
    if (map == null) {
      map = new HashMap<>();
    }

    Commit<? extends SetCommands.TtlCommand> previous = map.get(commit.operation().value());
    if (!isActive(commit, getTime())) {
      commit.clean();
      return false;
    } else if (!isActive(previous, commit.timestamp())) {
      map.put(commit.operation().value(), commit);
      previous.clean();
      return true;
    } else {
      commit.clean();
      return false;
    }
  }

  /**
   * Handles a remove commit.
   */
  @Apply(SetCommands.Remove.class)
  protected boolean remove(Commit<SetCommands.Remove> commit) {
    if (map == null) {
      commit.clean();
      return false;
    } else {
      Commit<? extends SetCommands.TtlCommand> previous = map.remove(commit.operation().value());
      if (previous == null) {
        commit.clean();
        return false;
      } else {
        previous.clean();
        return isActive(previous, commit.timestamp());
      }
    }
  }

  /**
   * Handles a count commit.
   */
  @Apply(SetCommands.Size.class)
  protected int size(Commit<SetCommands.Size> commit) {
    try {
      return map != null ? map.size() : 0;
    } finally {
      commit.close();
    }
  }

  /**
   * Handles an is empty commit.
   */
  @Apply(SetCommands.IsEmpty.class)
  protected boolean isEmpty(Commit<SetCommands.IsEmpty> commit) {
    try {
      return map == null || map.isEmpty();
    } finally {
      commit.close();
    }
  }

  /**
   * Handles a clear commit.
   */
  @Apply(SetCommands.Clear.class)
  protected void clear(Commit<SetCommands.Clear> commit) {
    if (map == null) {
      commit.clean();
    } else {
      map.clear();
    }
  }

}

@@ -2964,24 +2964,78 @@
 stamp())) %7B%0A
+      if (previous != null)%0A        previous.clean();%0A
       map.pu
@@ -3077,32 +3077,8 @@
 t);%0A
-      previous.clean();%0A
     

Fix NPE in set state machine add.