/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package de.christofreichardt.jaxws.securitypriceservice;

import de.christofreichardt.diagnosis.AbstractTracer;
import de.christofreichardt.diagnosis.Traceable;
import de.christofreichardt.diagnosis.TracerFactory;
import java.util.HashMap;
import java.util.Map;
import javax.enterprise.context.ApplicationScoped;

/**
 *
 * @author Christof Reichardt
 */
@ApplicationScoped
public class TransactionIDMap implements Traceable {
  private Map<String, Long> user2Id = new HashMap<>();
  
  synchronized public boolean isAllowed(String user, Long transactionId) {
    AbstractTracer tracer = getCurrentTracer();
    tracer.entry("boolean", this, "isAllowed(String user, Integer transactionId)");
    
    try {
      tracer.out().printfIndentln("user = %s", user);
      tracer.out().printfIndentln("transactionId = %d", transactionId);
      
      return !this.user2Id.containsKey(user) || transactionId > this.user2Id.get(user);
    }
    finally {
      tracer.wayout();
    }
  }
  
  synchronized public void setTransactionId(String user, Long transactionId) {
    AbstractTracer tracer = getCurrentTracer();
    tracer.entry("void", this, "setTransactionId(String user, Long transactionId)");
    
    try {
      tracer.out().printfIndentln("user = %s", user);
      tracer.out().printfIndentln("transactionId = %d", transactionId);
      
      if (!isAllowed(user, transactionId))
        throw new IllegalStateException("Illegal transactionId: " + transactionId + ".");
      
      this.user2Id.put(user, transactionId);
    }
    finally {
      tracer.wayout();
    }
  }
  
  synchronized public long nextTransactionId(String user) {
    AbstractTracer tracer = getCurrentTracer();
    tracer.entry("long", this, "nextTransactionId(String user)");
    
    try {
      tracer.out().printfIndentln("user = %s", user);
      
      return this.user2Id.get(user) + 1;
    }
    finally {
      tracer.wayout();
    }
  }

  @Override
  public AbstractTracer getCurrentTracer() {
    return TracerFactory.getInstance().getCurrentQueueTracer();
  }
}
