/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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 org.apache.activeblaze.impl.reliable;

import org.apache.activeblaze.wire.Packet;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Holds a buffer of Packets to replay
 */
public class ReliableBuffer {
    Map<String, ReliablePacket> idMap = new HashMap<String, ReliablePacket>();
    Map<Long, ReliablePacket> sequenceMap = new HashMap<Long, ReliablePacket>();
    private int bufferSize = 0;
    private ReliablePacket tail = null;
    private ReliablePacket root = null;

    /**
     * @return the bufferSize
     */
    public synchronized int getBufferSize() {
        return this.bufferSize;
    }

    /**
     * @return the number of packets in the Buffer
     */
    public synchronized int size() {
        return this.idMap.size();
    }

    /**
     * @return true if empty
     */
    public synchronized boolean isEmpty() {
        return this.idMap.isEmpty();
    }

    /**
     * Add a Packet
     */
    public synchronized void addPacket(Packet p) {
        ReliablePacket reliablePacket = new ReliablePacket(p);
        if (this.idMap.put(p.getId(), reliablePacket) == null) {
            this.sequenceMap.put(reliablePacket.getSequence(), reliablePacket);
            this.bufferSize++;
            if (this.root == null) {
                this.root = reliablePacket;
            } else {
                this.tail.linkAfter(reliablePacket);
            }
            this.tail = reliablePacket;
        }
    }

    /**
     * Add packet in order
     */
    public synchronized void addPacketInOrder(Packet p) {
        ReliablePacket reliablePacket = new ReliablePacket(p);
        if (this.idMap.put(p.getId(), reliablePacket) == null) {
            this.sequenceMap.put(reliablePacket.getSequence(), reliablePacket);
            this.bufferSize++;
            if (this.root == null) {
                this.root = reliablePacket;
                this.tail = reliablePacket;
            } else {
                if (this.root.getSequence().longValue() < reliablePacket.getSequence().longValue()) {
                    this.root.linkBefore(reliablePacket);
                    this.root = reliablePacket;
                } else if (this.tail.getSequence().longValue() > reliablePacket.getSequence().longValue()) {
                    ReliablePacket next = this.root;
                    ReliablePacket last = next;
                    while (next != null && reliablePacket.getSequence().longValue() > next.getSequence().longValue()) {
                        last = next;
                        next = (ReliablePacket) next.getNext();
                    }
                    last.linkAfter(reliablePacket);
                    if (this.tail == last) {
                        this.tail = reliablePacket;
                    }
                } else {
                    this.tail.linkAfter(reliablePacket);
                    this.tail = reliablePacket;
                }
            }
        }
    }

    /**
     * @return List of ordered Packets
     */
    public synchronized List<Packet> getOrderedBuffer() {
        List<Packet> result = new ArrayList<Packet>();
        if (size() > 1) {
            long sequence = -1;
            ReliablePacket next = this.root;
            ReliablePacket last = this.root;
            while (next != null) {
                last = next;
                next = (ReliablePacket) next.getNext();
                if (sequence == -1) {
                    sequence = last.getSequence().longValue();
                    result.add(last.getPacket());
                } else {
                    if (next != null) {
                        if (last.getSequence().longValue() + 1 == next.getSequence().longValue()) {
                            result.add(last.getPacket());
                        } else {
                            result.clear();
                            break;
                        }
                    }
                }
            }
        }
        return result;
    }

    /**
     * Get a Packet from the buffer
     *
     * @return the Packet
     */
    public synchronized Packet getPacket(String id) {
        ReliablePacket reliablePacket = this.idMap.get(id);
        return reliablePacket != null ? reliablePacket.getPacket() : null;
    }

    /**
     * Get a Packet from the buffer
     *
     * @return the Packet
     */
    public synchronized Packet getPacket(long id) {
        ReliablePacket reliablePacket = this.sequenceMap.get(new Long(id));
        return reliablePacket != null ? reliablePacket.getPacket() : null;
    }

    /**
     * Get the next Packet form the buffer
     *
     * @return the next Packet from the buffer
     */
    public synchronized Packet getNext(Packet p) {
        ReliablePacket next = getNext(this.idMap.get(p.getId()));
        return next != null ? next.getPacket() : null;
    }

    /**
     * Get a list of Packetd from the buffer
     *
     * @return the list of type <Code>Packet</Code>
     */
    public synchronized List<Packet> getPackets(long start, long end) {
        List<Packet> result = new ArrayList<Packet>();
        ReliablePacket reliablePacket = this.sequenceMap.get(new Long(start));
        if (reliablePacket != null) {
            result.add(reliablePacket.getPacket());
            if (end >= start) {
                while (reliablePacket != null) {
                    reliablePacket = (ReliablePacket) reliablePacket.getNext();
                    if (reliablePacket != null) {
                        if (reliablePacket.getSequence().longValue() <= end) {
                            result.add(reliablePacket.getPacket());
                        } else {
                            break;
                        }
                    }
                }
            }
        }
        return result;
    }

    /**
     * Remove a packet from the buffer
     */
    public synchronized void removePacket(Packet p) {
        removePacket(p.getId());
    }

    /**
     * Remove a packet from the buffer
     *
     * @param id -
     *           the id of the Packet
     */
    public synchronized void removePacket(String id) {
        ReliablePacket reliablePacket = this.idMap.remove(id);
        removeReliablePacket(reliablePacket);
    }

    /**
     * Remove a Packet from the buffer
     */
    public synchronized void removePacket(long sequenceNumber) {
        ReliablePacket reliablePacket = this.sequenceMap.remove(new Long(sequenceNumber));
        removeReliablePacket(reliablePacket);
    }

    /**
     * Remove Packets from the buffer
     */
    public synchronized void removePackets(long start, long end) {
        ReliablePacket packet = this.root;
        while (packet != null) {
            ReliablePacket remove = packet;
            packet = getNext(packet);
            long sequence = remove.getSequence().longValue();
            if (start <= sequence && end >= sequence) {
                removeReliablePacket(remove);
            }
            if (end < sequence) {
                break;
            }
        }
    }

    /**
     * clear the buffer
     */
    public synchronized void clear() {
        this.idMap.clear();
        this.sequenceMap.clear();
        this.root = null;
        this.tail = null;
        this.bufferSize = 0;
    }

    private ReliablePacket getNext(ReliablePacket reliablePacket) {
        ReliablePacket result = null;
        if (reliablePacket != null) {
            result = ((ReliablePacket) reliablePacket.getNext());
        }
        return result;
    }

    private void removeReliablePacket(ReliablePacket reliablePacket) {
        if (reliablePacket != null) {
            this.idMap.remove(reliablePacket.getId());
            this.sequenceMap.remove(reliablePacket.getSequence());
            if (reliablePacket == this.root) {
                this.root = (ReliablePacket) reliablePacket.getNext();
            }
            if (reliablePacket == this.tail) {
                this.tail = (ReliablePacket) reliablePacket.getPrevious();
            }
            reliablePacket.unlink();
            this.bufferSize--;
        }
    }
}
