package ru.szhernovoy.nonblock;

import com.sun.javafx.sg.prism.NGShape;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.BiFunction;

/**
 * Created by szhernovoy on 27.10.2016.
 */
public class Cash<E extends Model> {

    private Map<Integer,E> cash = new ConcurrentHashMap<>();

    public void add(E e){

        this.cash.put(e.getId(),e);

    }

    public void delete(E e){
        this.cash.remove(e.getId());

    }

    public void update(E newModel) throws OptimisticException {
        this.cash.computeIfPresent(newModel.getId(), new BiFunction<Integer, E, E>() {
            @Override
            public E apply(Integer integer, E oldModel) {
                if (oldModel.getVersion() == newModel.getVersion()) {
                    newModel.increment();
                    return newModel;
                } else {
                    throw new OptimisticException("version is uncorrect");
                }
            }
        });
    }

    public E check(E newModel, E oldModel) {
        if (oldModel.getVersion() == newModel.getVersion()) {
            newModel.increment();
            this.add(newModel);
            return newModel;
        } else {
            throw new OptimisticException("version is uncorrect");
        }
    }


}

@@ -1003,310 +1003,6 @@
  %7D%0A%0A
-    public E check(E newModel, E oldModel) %7B%0A        if (oldModel.getVersion() == newModel.getVersion()) %7B%0A            newModel.increment();%0A            this.add(newModel);%0A            return newModel;%0A        %7D else %7B%0A            throw new OptimisticException(%22version is uncorrect%22);%0A        %7D%0A    %7D%0A%0A%0A
 %7D%0A

update cash