/*
 * Copyright 2012 Tamas Blummer tamas@bitsofproof.com
 *
 * 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 com.bitsofproof.supernode.core;

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

import com.bitsofproof.supernode.model.TxOut;

public class ImplementTxOutCacheDelta implements TxOutCache
{
	private final TxOutCache delegate;
	private final ImplementTxOutCache added = new ImplementTxOutCache ();
	private final Map<String, HashSet<Long>> removed = new HashMap<String, HashSet<Long>> ();

	public ImplementTxOutCacheDelta (TxOutCache cache)
	{
		delegate = cache;
	}

	@Override
	public TxOut get (String hash, Long ix)
	{
		if ( removed.containsKey (hash) && removed.get (hash).contains (ix) )
		{
			return null;
		}
		TxOut a = added.get (hash, ix);
		if ( a == null )
		{
			return delegate.get (hash, ix);
		}
		return a;
	}

	@Override
	public void copy (TxOutCache other, String hash)
	{
		if ( other != delegate )
		{
			throw new RuntimeException ("not implemented");
		}
	}

	@Override
	public void add (TxOut out)
	{
		added.add (out);
	}

	@Override
	public void remove (String hash, Long ix)
	{
		HashSet<Long> rs = removed.get (hash);
		if ( rs == null )
		{
			rs = new HashSet<Long> ();
			removed.put (hash, rs);
		}
		rs.add (ix);
	}
}

@@ -1574,16 +1574,199 @@
 out)%0A%09%7B%0A
+%09%09if ( removed.containsKey (out.getTxHash ()) && removed.get (out.getTxHash ()).contains (out.getIx ()) )%0A%09%09%7B%0A%09%09%09removed.get (out.getTxHash ()).remove (out.getIx ());%0A%09%09%7D%0A%09%09else%0A%09%09%7B%0A%09
 %09%09added.
@@ -1776,16 +1776,20 @@
  (out);%0A
+%09%09%7D%0A
 %09%7D%0A%0A%09@Ov
@@ -1841,16 +1841,102 @@
  ix)%0A%09%7B%0A
+%09%09if ( added.get (hash, ix) != null )%0A%09%09%7B%0A%09%09%09added.remove (hash, ix);%0A%09%09%7D%0A%09%09else%0A%09%09%7B%0A%09
 %09%09HashSe
@@ -1966,24 +1966,25 @@
 t (hash);%0A%09%09
+%09
 if ( rs == n
@@ -1989,23 +1989,25 @@
  null )%0A
+%09
 %09%09%7B%0A%09%09%09
+%09
 rs = new
@@ -2025,16 +2025,17 @@
 ng%3E ();%0A
+%09
 %09%09%09remov
@@ -2055,18 +2055,20 @@
  rs);%0A%09%09
+%09
 %7D%0A
+%09
 %09%09rs.add
@@ -2074,13 +2074,17 @@
 d (ix);%0A
+%09%09%7D%0A
 %09%7D%0A%7D%0A

fix add removed and remove added