/*
 * Copyright 2016 higherfrequencytrading.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 net.openhft.chronicle.bytes.ref;

import net.openhft.chronicle.bytes.BytesStore;
import net.openhft.chronicle.core.Jvm;
import org.jetbrains.annotations.NotNull;

import java.lang.ref.WeakReference;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.Set;

public class BinaryLongReference implements LongReference {
    private BytesStore bytes;
    private long offset;

    private static Set<WeakReference<BinaryLongReference>> binaryLongReferences;

    static {
        if (Jvm.isDebug()) {
            binaryLongReferences = Collections.newSetFromMap(new IdentityHashMap<>());
        }
    }

    /**
     * only used for testing
     */
    public static void forceAllToNotCompleteState() {
        binaryLongReferences.forEach(x -> {
            BinaryLongReference binaryLongReference = x.get();
            if (binaryLongReference != null) {
                binaryLongReference.setValue(1 << 31 | binaryLongReference.getValue());
            }
        });
    }


    @Override
    public void bytesStore(@NotNull BytesStore bytes, long offset, long length) {
        if (length != maxSize())
            throw new IllegalArgumentException();

        this.bytes = bytes.bytesStore();
        this.offset = offset;
    }

    @Override
    public BytesStore bytesStore() {
        return bytes;
    }

    @Override
    public long offset() {
        return offset;
    }

    @Override
    public long maxSize() {
        return 8;
    }

    @NotNull
    public String toString() {
        return bytes == null ? "bytes is null" : "value: " + getValue();
    }

    @Override
    public long getValue() {
        return bytes.readLong(offset);
    }

    @Override
    public void setValue(long value) {
        bytes.writeLong(offset, value);
    }

    @Override
    public long getVolatileValue() {
        return bytes.readVolatileLong(offset);
    }

    @Override
    public void setOrderedValue(long value) {
        bytes.writeOrderedLong(offset, value);
    }

    @Override
    public long addValue(long delta) {
        return bytes.addAndGetLong(offset, delta);
    }

    @Override
    public long addAtomicValue(long delta) {
        return addValue(delta);
    }

    @Override
    public boolean compareAndSwapValue(long expected, long value) {
        if (Jvm.isDebug() && (value & 1 << 31) != 0)
            binaryLongReferences.add(new WeakReference<BinaryLongReference>(this));

        return bytes.compareAndSwapLong(offset, expected, value);
    }
}

@@ -696,47 +696,8 @@
 re;%0A
-import net.openhft.chronicle.core.Jvm;%0A
 impo
@@ -788,27 +788,19 @@
 va.util.
-Collections
+Set
 ;%0Aimport
@@ -814,42 +814,35 @@
 til.
-IdentityHashMap;%0Aimport java.util.
+concurrent.CopyOnWriteArray
 Set;
@@ -912,58 +912,55 @@
    p
-rivate BytesStore bytes;%0A    private long offset;%0A
+ublic static final long LONG_NOT_COMPLETE = -1;
 %0A   
@@ -1041,55 +1041,152 @@
 es;%0A
-%0A    static %7B%0A        if (Jvm.isDebu
+    private BytesStore bytes;%0A    private long offset;%0A%0A    /**%0A     * only used for testing%0A     */%0A    public static void startCollectin
 g()
-)
  %7B%0A
-    
     
@@ -1216,69 +1216,36 @@
 s = 
-Collections.newSetFromMap(new IdentityHashMap%3C%3E());%0A        %7D
+new CopyOnWriteArraySet%3C%3E();
 %0A   
@@ -1550,83 +1550,96 @@
 lue(
-1 %3C%3C 31 %7C binaryLongReference.getValue());%0A            %7D%0A        %7D);%0A    %7D%0A
+LONG_NOT_COMPLETE);%0A            %7D%0A        %7D);%0A        binaryLongReferences = null;%0A    %7D
 %0A%0A  
@@ -2951,47 +2951,66 @@
 if (
-Jvm.isDebug() && (value & 1 %3C%3C 31) != 0
+value == LONG_NOT_COMPLETE && binaryLongReferences != null
 )%0A  
@@ -3062,35 +3062,16 @@
 ference%3C
-BinaryLongReference
 %3E(this))
@@ -3072,17 +3072,16 @@
 this));%0A
-%0A
         

Fix a bug where it doesn't recover on failure while creating the index2index