001/*
002 * ModeShape (http://www.modeshape.org)
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *       http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package org.modeshape.schematic.internal.delta;
017
018import org.modeshape.schematic.document.Path;
019import org.modeshape.schematic.internal.HashCode;
020import org.modeshape.schematic.internal.document.MutableArray;
021import org.modeshape.schematic.internal.document.MutableDocument;
022
023/**
024 * An atomic array add operation for SchematicValueDelta.
025 * 
026 * @author Randall Hauch <rhauch@redhat.com> (C) 2011 Red Hat Inc.
027 */
028public class RemoveAtIndexOperation extends ArrayOperation {
029
030    protected final int index;
031    protected transient Object actualValue = null;
032
033    public RemoveAtIndexOperation( Path path,
034                                   int index ) {
035        super(path, HashCode.compute(path, index));
036        this.index = index;
037    }
038
039    @Override
040    public RemoveAtIndexOperation clone() {
041        return new RemoveAtIndexOperation(getParentPath(), index);
042    }
043
044    public int getIndex() {
045        return index;
046    }
047
048    public Object getRemovedValue() {
049        return actualValue;
050    }
051
052    @Override
053    public void rollback( MutableDocument delegate ) {
054        if (actualValue != null) {
055            MutableArray array = mutableParent(delegate);
056            array.add(index, actualValue);
057        }
058    }
059
060    @Override
061    public void replay( MutableDocument delegate ) {
062        MutableArray array = mutableParent(delegate);
063        actualValue = array.remove(index);
064    }
065
066    @Override
067    public String toString() {
068        return "Remove at '" + parentPath + "' the value at index " + index;
069    }
070
071    @Override
072    public int hashCode() {
073        return super.hashCode();
074    }
075
076    @Override
077    public boolean equals( Object obj ) {
078        if (obj instanceof RemoveAtIndexOperation) {
079            RemoveAtIndexOperation other = (RemoveAtIndexOperation)obj;
080            return index == other.index && equalsIfNotNull(getParentPath(), other.getParentPath());
081
082        }
083        return false;
084    }
085}