package com.njzscloud.common.core.thread;

import lombok.extern.slf4j.Slf4j;

import java.util.*;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;

@Slf4j
@SuppressWarnings("unchecked")
public class WindowBlockingQueue<E> extends AbstractQueue<E> implements BlockingQueue<E> {

    private final int windowCapacity;
    private final int totalCapacity;
    private final AtomicInteger totalElementCount = new AtomicInteger();
    private final AtomicInteger windowElementCount = new AtomicInteger();
    private final AtomicInteger standbyElementCount = new AtomicInteger();
    private final ReentrantLock takeLock = new ReentrantLock();
    private final Condition notEmpty = takeLock.newCondition();
    private final ReentrantLock putLock = new ReentrantLock();
    private final Condition notFull = putLock.newCondition();
    private Node<E> head;
    private Node<E> border;
    private Node<E> last;

    public WindowBlockingQueue() {
        this(Integer.MAX_VALUE, Integer.MAX_VALUE);
    }

    public WindowBlockingQueue(int totalCapacity, int windowCapacity) {
        if (windowCapacity <= 0 || totalCapacity < windowCapacity) throw new IllegalArgumentException();
        this.totalCapacity = totalCapacity;
        this.windowCapacity = windowCapacity;
        head = border = last = new Node<>(null);
    }

    public WindowBlockingQueue(Collection<? extends E> c) {
        this(Integer.MAX_VALUE, Integer.MAX_VALUE);
        final ReentrantLock putLock = this.putLock;
        putLock.lock();
        try {
            int n = 0;
            for (E e : c) {
                if (e == null)
                    throw new NullPointerException();
                if (n == windowCapacity)
                    throw new IllegalStateException("Queue full");
                enqueue(new Node<>(e));
                ++n;
            }
            windowElementCount.set(n);
        } finally {
            putLock.unlock();
        }
    }

    private void signalNotEmpty() {
        takeLock.lock();
        try {
            notEmpty.signal();
        } finally {
            takeLock.unlock();
        }
    }

    private void signalNotFull() {
        putLock.lock();
        try {
            notFull.signal();
        } finally {
            putLock.unlock();
        }
    }

    private void enqueue(Node<E> node) {
        last = last.next = node;
        totalElementCount.incrementAndGet();
    }

    private E dequeue() {
        Node<E> h = head;
        Node<E> first = h.next;
        h.next = h;
        head = first;
        E x = first.item;
        first.item = null;
        totalElementCount.decrementAndGet();
        return x;
    }

    void fullyLock() {
        putLock.lock();
        takeLock.lock();
    }

    void fullyUnlock() {
        takeLock.unlock();
        putLock.unlock();
    }

    public int size() {
        return windowElementCount.get();
    }

    public int remainingCapacity() {
        return windowCapacity - windowElementCount.get();
    }

    public void put(E e) throws InterruptedException {
        if (e == null) throw new NullPointerException();
        int c = -1;
        Node<E> node = new Node<>(e);
        final ReentrantLock putLock = this.putLock;
        final AtomicInteger count = this.windowElementCount;
        putLock.lockInterruptibly();
        try {
            while (count.get() == windowCapacity) {
                notFull.await();
            }
            enqueue(node);
            c = count.getAndIncrement();
            if (c + 1 < windowCapacity)
                notFull.signal();
        } finally {
            putLock.unlock();
        }
        if (c == 0)
            signalNotEmpty();
    }

    public boolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException {
        if (e == null) throw new NullPointerException();
        long nanos = unit.toNanos(timeout);
        int c = -1;
        final ReentrantLock putLock = this.putLock;
        final AtomicInteger count = this.windowElementCount;
        putLock.lockInterruptibly();
        try {
            while (count.get() == windowCapacity) {
                if (nanos <= 0)
                    return false;
                nanos = notFull.awaitNanos(nanos);
            }
            enqueue(new Node<E>(e));
            c = count.getAndIncrement();
            if (c + 1 < windowCapacity)
                notFull.signal();
        } finally {
            putLock.unlock();
        }
        if (c == 0)
            signalNotEmpty();
        return true;
    }

    public boolean offer(E e) {
        if (e == null) throw new NullPointerException();
        boolean offered = false;
        int c = windowElementCount.get();
        if (c == windowCapacity) return offered;
        Node<E> node = new Node<>(e);
        final ReentrantLock putLock = this.putLock;
        putLock.lock();
        try {
            if (windowElementCount.get() < windowCapacity) {
                enqueue(node);
                offered = true;
                c = windowElementCount.incrementAndGet();
                border = node;
                if (c < windowCapacity) notFull.signal();
            }
        } finally {
            // log.debug("1、添加元素：总数：{}、窗口区：{}、备份区：{}", totalElementCount.get(), windowElementCount.get(), standbyElementCount.get());
            putLock.unlock();
        }
        if (c > 0) signalNotEmpty();
        return offered;
    }

    public boolean offerStandby(E e) {
        if (e == null) throw new NullPointerException();
        boolean offered = false;
        int c = totalElementCount.get();
        if (c == totalCapacity) return offered;
        Node<E> node = new Node<>(e);
        putLock.lock();
        try {
            if (totalElementCount.get() < totalCapacity) {
                enqueue(node);
                offered = true;
                c = windowElementCount.get();
                if (c + 1 <= windowCapacity) {
                    border = node;
                    windowElementCount.incrementAndGet();
                } else {
                    standbyElementCount.incrementAndGet();
                }
                if (c + 1 < windowCapacity) notFull.signal();
            }
            c = windowElementCount.get();
        } finally {
            log.debug("3、添加元素：总数：{}、窗口区：{}、备份区：{}", totalElementCount.get(), windowElementCount.get(), standbyElementCount.get());
            putLock.unlock();
        }
        if (c != 0) signalNotEmpty();
        return offered;
    }

    public E take() throws InterruptedException {
        E x;
        int c = -1;
        takeLock.lockInterruptibly();
        try {
            while (windowElementCount.get() == 0) {
                notEmpty.await();
            }
            x = dequeue();
            if (border.next == null) {
                c = windowElementCount.decrementAndGet();
            } else {
                border = border.next;
                standbyElementCount.decrementAndGet();
                c = windowElementCount.get();
            }
            if (c > 0) notEmpty.signal();
        } finally {
            log.debug("1、提取元素：总数：{}、窗口：{}、备份区：{}", totalElementCount.get(), windowElementCount.get(), standbyElementCount.get());
            takeLock.unlock();
        }
        if (c != windowCapacity) signalNotFull();
        return x;
    }

    public E poll(long timeout, TimeUnit unit) throws InterruptedException {
        E x = null;
        int c = -1;
        long nanos = unit.toNanos(timeout);
        takeLock.lockInterruptibly();
        try {
            while (windowElementCount.get() == 0) {
                if (nanos <= 0) return null;
                nanos = notEmpty.awaitNanos(nanos);
            }
            x = dequeue();
            if (border.next == null) {
                c = windowElementCount.decrementAndGet();
            } else {
                border = border.next;
                standbyElementCount.decrementAndGet();
                c = windowElementCount.get();
            }
            if (c > 0) notEmpty.signal();
        } finally {
            // log.debug("2、提取元素：总数：{}、窗口：{}、备份区：{}", totalElementCount.get(), windowElementCount.get(), standbyElementCount.get());
            takeLock.unlock();
        }
        if (c != windowCapacity) signalNotFull();
        return x;
    }

    public E poll() {
        if (windowElementCount.get() == 0) return null;
        E x = null;
        int c = -1;
        takeLock.lock();
        try {
            if (windowElementCount.get() > 0) {
                x = dequeue();
                if (border.next == null) {
                    c = windowElementCount.decrementAndGet();
                } else {
                    border = border.next;
                    standbyElementCount.decrementAndGet();
                    c = windowElementCount.get();
                }
                if (c > 0) notEmpty.signal();
            }
        } finally {
            log.debug("3、提取元素：总数：{}、窗口：{}、备份区：{}", totalElementCount.get(), windowElementCount.get(), standbyElementCount.get());
            takeLock.unlock();
        }
        if (c != windowCapacity) signalNotFull();
        return x;
    }

    public E peek() {
        if (windowElementCount.get() == 0)
            return null;
        takeLock.lock();
        try {
            Node<E> first = head.next;
            if (first == null)
                return null;
            else
                return first.item;
        } finally {
            takeLock.unlock();
        }
    }

    void unlink(Node<E> p, Node<E> trail, boolean overBorder) {
        totalElementCount.getAndDecrement();
        if (p == border || !overBorder) {
            if (border.next == null) {
                windowElementCount.getAndDecrement();
            } else {
                border = border.next;
                standbyElementCount.decrementAndGet();
            }
        } else {
            standbyElementCount.decrementAndGet();
        }
        p.item = null;
        trail.next = p.next;
        if (last == p) last = trail;

        if (windowElementCount.get() == windowCapacity) notFull.signal();
    }

    public boolean remove(Object o) {
        if (o == null) return false;
        fullyLock();
        try {
            boolean overBorder = false;
            for (Node<E> trail = head, p = trail.next;
                 p != null;
                 trail = p, p = p.next) {
                if (!overBorder) overBorder = trail == border;
                if (o.equals(p.item)) {
                    unlink(p, trail, overBorder);
                    return true;
                }
            }
            return false;
        } finally {
            log.debug("1、删除元素：总数：{}、窗口：{}、备份区：{}", totalElementCount.get(), windowElementCount.get(), standbyElementCount.get());
            fullyUnlock();
        }
    }

    public boolean contains(Object o) {
        if (o == null) return false;
        fullyLock();
        try {
            for (Node<E> p = head.next; p != null; p = p.next)
                if (o.equals(p.item))
                    return true;
            return false;
        } finally {
            fullyUnlock();
        }
    }

    public Object[] toArray() {
        fullyLock();
        try {
            int size = windowElementCount.get();
            Object[] a = new Object[size];
            int k = 0;
            for (Node<E> p = head.next; p != null; p = p.next)
                a[k++] = p.item;
            return a;
        } finally {
            fullyUnlock();
        }
    }

    public <T> T[] toArray(T[] a) {
        fullyLock();
        try {
            int size = windowElementCount.get();
            if (a.length < size)
                a = (T[]) java.lang.reflect.Array.newInstance
                        (a.getClass().getComponentType(), size);

            int k = 0;
            for (Node<E> p = head.next; p != null; p = p.next)
                a[k++] = (T) p.item;
            if (a.length > k)
                a[k] = null;
            return a;
        } finally {
            fullyUnlock();
        }
    }

    public String toString() {
        fullyLock();
        try {
            Node<E> p = head.next;
            if (p == null)
                return "[]";

            StringBuilder sb = new StringBuilder();
            sb.append('[');
            for (; ; ) {
                E e = p.item;
                sb.append(e == this ? "(this Collection)" : e);
                p = p.next;
                if (p == null)
                    return sb.append(']').toString();
                sb.append(',').append(' ');
            }
        } finally {
            fullyUnlock();
        }
    }

    public void clear() {
        fullyLock();
        try {
            for (Node<E> p, h = head; (p = h.next) != null; h = p) {
                h.next = h;
                p.item = null;
            }
            head = last;
            totalElementCount.getAndSet(0);
            standbyElementCount.getAndSet(0);
            if (windowElementCount.getAndSet(0) == windowCapacity) notFull.signal();
        } finally {
            fullyUnlock();
        }
    }

    public int drainTo(Collection<? super E> c) {
        return drainTo(c, Integer.MAX_VALUE);
    }

    public int drainTo(Collection<? super E> c, int maxElements) {
        if (c == null)
            throw new NullPointerException();
        if (c == this)
            throw new IllegalArgumentException();
        if (maxElements <= 0)
            return 0;
        boolean signalNotFull = false;
        final ReentrantLock takeLock = this.takeLock;
        takeLock.lock();
        try {
            int n = Math.min(maxElements, windowElementCount.get());

            Node<E> h = head;
            int i = 0;
            try {
                while (i < n) {
                    Node<E> p = h.next;
                    c.add(p.item);
                    p.item = null;
                    h.next = h;
                    h = p;
                    ++i;

                    if (border.next == null) {
                        windowElementCount.decrementAndGet();
                    } else {
                        border = border.next;
                        standbyElementCount.decrementAndGet();
                    }
                }
                return n;
            } finally {
                if (i > 0) {
                    head = h;
                    totalElementCount.getAndAdd(-i);
                    signalNotFull = (windowElementCount.get() == windowCapacity);
                }
            }
        } finally {
            takeLock.unlock();
            if (signalNotFull)
                signalNotFull();
        }
    }

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

    public Spliterator<E> spliterator() {
        return new LBQSpliterator<E>(this);
    }

    static class Node<E> {
        E item;

        /**
         * One of:
         * - the real successor Node
         * - this Node, meaning the successor is head.next
         * - null, meaning there is no successor (this is the last node)
         */
        Node<E> next;

        Node(E x) {
            item = x;
        }
    }

    static final class LBQSpliterator<E> implements Spliterator<E> {
        static final int MAX_BATCH = 1 << 25;
        final WindowBlockingQueue<E> queue;
        Node<E> current;
        int batch;
        boolean exhausted;
        long est;

        LBQSpliterator(WindowBlockingQueue<E> queue) {
            this.queue = queue;
            this.est = queue.size();
        }

        public long estimateSize() {
            return est;
        }

        public Spliterator<E> trySplit() {
            Node<E> h;
            final WindowBlockingQueue<E> q = this.queue;
            int b = batch;
            int n = (b <= 0) ? 1 : (b >= MAX_BATCH) ? MAX_BATCH : b + 1;
            if (!exhausted &&
                    ((h = current) != null || (h = q.head.next) != null) &&
                    h.next != null) {
                Object[] a = new Object[n];
                int i = 0;
                Node<E> p = current;
                q.fullyLock();
                try {
                    if (p != null || (p = q.head.next) != null) {
                        do {
                            if ((a[i] = p.item) != null)
                                ++i;
                        } while ((p = p.next) != null && i < n);
                    }
                } finally {
                    q.fullyUnlock();
                }
                if ((current = p) == null) {
                    est = 0L;
                    exhausted = true;
                } else if ((est -= i) < 0L)
                    est = 0L;
                if (i > 0) {
                    batch = i;
                    return Spliterators.spliterator
                            (a, 0, i, Spliterator.ORDERED | Spliterator.NONNULL |
                                    Spliterator.CONCURRENT);
                }
            }
            return null;
        }

        public void forEachRemaining(Consumer<? super E> action) {
            if (action == null) throw new NullPointerException();
            final WindowBlockingQueue<E> q = this.queue;
            if (!exhausted) {
                exhausted = true;
                Node<E> p = current;
                do {
                    E e = null;
                    q.fullyLock();
                    try {
                        if (p == null)
                            p = q.head.next;
                        while (p != null) {
                            e = p.item;
                            p = p.next;
                            if (e != null)
                                break;
                        }
                    } finally {
                        q.fullyUnlock();
                    }
                    if (e != null)
                        action.accept(e);
                } while (p != null);
            }
        }

        public boolean tryAdvance(Consumer<? super E> action) {
            if (action == null) throw new NullPointerException();
            final WindowBlockingQueue<E> q = this.queue;
            if (!exhausted) {
                E e = null;
                q.fullyLock();
                try {
                    if (current == null)
                        current = q.head.next;
                    while (current != null) {
                        e = current.item;
                        current = current.next;
                        if (e != null)
                            break;
                    }
                } finally {
                    q.fullyUnlock();
                }
                if (current == null)
                    exhausted = true;
                if (e != null) {
                    action.accept(e);
                    return true;
                }
            }
            return false;
        }

        public int characteristics() {
            return Spliterator.ORDERED | Spliterator.NONNULL |
                    Spliterator.CONCURRENT;
        }
    }

    private class Itr implements Iterator<E> {
        private Node<E> current;
        private Node<E> lastRet;
        private E currentElement;

        Itr() {
            fullyLock();
            try {
                current = head.next;
                if (current != null)
                    currentElement = current.item;
            } finally {
                fullyUnlock();
            }
        }

        public boolean hasNext() {
            return current != null;
        }

        /**
         * Returns the next live successor of p, or null if no such.
         * <p>
         * Unlike other traversal methods, iterators need to handle both:
         * - dequeued nodes (p.next == p)
         * - (possibly multiple) interior removed nodes (p.item == null)
         */
        private Node<E> nextNode(Node<E> p) {
            for (; ; ) {
                Node<E> s = p.next;
                if (s == p)
                    return head.next;
                if (s == null || s.item != null)
                    return s;
                p = s;
            }
        }

        public E next() {
            fullyLock();
            try {
                if (current == null)
                    throw new NoSuchElementException();
                E x = currentElement;
                lastRet = current;
                current = nextNode(current);
                currentElement = (current == null) ? null : current.item;
                return x;
            } finally {
                fullyUnlock();
            }
        }

        public void remove() {
            if (lastRet == null)
                throw new IllegalStateException();
            fullyLock();
            try {
                Node<E> node = lastRet;
                lastRet = null;
                boolean overBorder = false;
                for (Node<E> trail = head, p = trail.next;
                     p != null;
                     trail = p, p = p.next) {
                    if (!overBorder) overBorder = trail == border;
                    if (p == node) {
                        unlink(p, trail, overBorder);
                        break;
                    }
                }
            } finally {
                fullyUnlock();
            }
        }
    }
}
