/*
 * 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.felix.resolver.util;

import java.lang.reflect.Array;
import java.util.*;

@SuppressWarnings("NullableProblems")
public class CopyOnWriteList<E> implements List<E>, Cloneable, RandomAccess {

    Object[] data;

    public CopyOnWriteList() {
        data = new Object[0];
    }

    public CopyOnWriteList(CopyOnWriteList<? extends E> col) {
        data = col.data;
    }

    public CopyOnWriteList(Collection<? extends E> col) {
        data = col.toArray(new Object[col.size()]);
    }

    public int size() {
        return data.length;
    }

    @SuppressWarnings("unchecked")
    public E get(int index) {
        return (E) data[index];
    }

    @SuppressWarnings("unchecked")
    public E set(int index, E element) {
        data = CopyOnWriteSet.copyOf(data, data.length);
        E prev = (E) data[index];
        data[index] = element;
        return prev;
    }

    public void add(int index, E element) {
        Object[] elements = data;
        int len = elements.length;
        Object[] newElements = new Object[len + 1];
        int numMoved = len - index;
        if (index > 0) {
            System.arraycopy(elements, 0, newElements, 0, index);
        }
        if (numMoved > 0) {
            System.arraycopy(elements, index, newElements, index + 1, numMoved);
        }
        newElements[index] = element;
        data = newElements;
    }

    @SuppressWarnings("unchecked")
    public E remove(int index) {
        Object[] elements = data;
        int len = elements.length;
        E oldValue = (E) elements[index];
        Object[] newElements = new Object[len - 1];
        int numMoved = len - index - 1;
        if (index > 0) {
            System.arraycopy(elements, 0, newElements, 0, index);
        }
        if (numMoved > 0) {
            System.arraycopy(elements, index + 1, newElements, index, numMoved);
        }
        data = newElements;
        return oldValue;
    }

    public boolean isEmpty() {
        return size() == 0;
    }

    public boolean contains(Object o) {
        return indexOf(o) >= 0;
    }

    public Iterator<E> iterator() {
        return new CopyOnWriteListIterator(0);
    }

    class CopyOnWriteListIterator implements ListIterator<E> {
        int idx;
        CopyOnWriteListIterator(int idx) {
            this.idx = idx;
        }

        @Override
        public boolean hasNext() {
            return idx < data.length;
        }

        @Override
        public E next() {
            if (!hasNext()) {
                throw new NoSuchElementException();
            }
            return (E) data[idx++];
        }

        @Override
        public boolean hasPrevious() {
            return idx >= 0;
        }

        @Override
        public E previous() {
            if (!hasPrevious()) {
                throw new NoSuchElementException();
            }
            return (E) data[idx--];
        }

        @Override
        public int nextIndex() {
            return idx;
        }

        @Override
        public int previousIndex() {
            return idx - 1;
        }

        @Override
        public void remove() {
            CopyOnWriteList.this.remove(--idx);
        }

        @Override
        public void set(E e) {
            new UnsupportedOperationException();
        }

        @Override
        public void add(E e) {
            CopyOnWriteList.this.add(idx, e);
        }
    }

    public Object[] toArray() {
        return data.clone();
    }

    @SuppressWarnings("unchecked")
    public <T> T[] toArray(T[] a) {
        int size = data.length;
        if (a.length < size)
            // Make a new array of a's runtime type, but my contents:
            return (T[]) CopyOnWriteSet.copyOf(data, size, a.getClass());
        System.arraycopy(data, 0, a, 0, size);
        if (a.length > size)
            a[size] = null;
        return a;
    }

    public boolean add(E e) {
        add(size(), e);
        return true;
    }

    public boolean remove(Object o) {
        int index;
        if ((index = indexOf(o)) >= 0) {
            remove(index);
            return true;
        }
        return false;
    }

    public boolean containsAll(Collection<?> c) {
        Object[] elements = data;
        int len = elements.length;
        for (Object e : c) {
            if (indexOf(e, elements, len) < 0)
                return false;
        }
        return true;
    }

    private static int indexOf(Object o, Object[] d, int len) {
        if (o == null) {
            for (int i = len; i-- > 0;) {
                if (d[i] == null)
                    return i;
            }
        } else {
            for (int i = len; i-- > 0;) {
                if (o.equals(d[i]))
                    return i;
            }
        }
        return -1;
    }

    public boolean addAll(Collection<? extends E> c) {
        return addAll(size(), c);
    }

    public boolean addAll(int index, Collection<? extends E> c) {
        for (E e : c) {
            add(index++, e);
        }
        return !(c.isEmpty());
    }

    public boolean removeAll(Collection<?> c) {
        boolean modified = false;
        Object[] d = data, o = data;
        int idx = 0;
        for (int i = 0, l = o.length; i < l; i++) {
            if (c.contains(o[i])) {
                if (!modified) {
                    d = o.clone();
                    idx = i;
                    modified = true;
                }
            } else if (modified) {
                d[idx++] = o[i];
            }
        }
        if (modified) {
            data = CopyOnWriteSet.copyOf(d, idx);
        }
        return modified;
    }

    public boolean retainAll(Collection<?> c) {
        throw new UnsupportedOperationException();
    }

    public void clear() {
        data = new Object[0];
    }

    public int indexOf(Object o) {
        return indexOf(o, data, data.length);
    }

    public int lastIndexOf(Object o) {
        throw new UnsupportedOperationException();
    }

    public ListIterator<E> listIterator() {
        return new CopyOnWriteListIterator(0);
    }

    public ListIterator<E> listIterator(int index) {
        return new CopyOnWriteListIterator(index);
    }

    public List<E> subList(int fromIndex, int toIndex) {
        throw new UnsupportedOperationException();
    }

    /**
     * Clone this object
     *
     * @return a cloned object.
     */
    @Override
    @SuppressWarnings("unchecked")
    public CopyOnWriteList<E> clone() {
        try {
            return (CopyOnWriteList<E>) super.clone();
        } catch (CloneNotSupportedException exc) {
            InternalError e = new InternalError();
            e.initCause(exc);
            throw e; //should never happen since we are cloneable
        }
    }

    @Override
    public int hashCode() {
        return Arrays.hashCode(data);
    }

    @Override
    public boolean equals(Object o) {
        if (!(o instanceof CopyOnWriteList)) {
            return false;
        }
        Object[] o1 = data;
        Object[] o2 = ((CopyOnWriteList) o).data;
        if (o1 == o2) {
            return true;
        }
        int i;
        if ((i = o1.length) != o2.length) {
            return false;
        }
        while (i-- > 0) {
            Object v1 = o1[i];
            Object v2 = o2[i];
            if (!(v1 == null ? v2 == null : v1.equals(v2)))
                return false;
        }
        return true;
    }
}
