package ch.polgrabia.demos.spring_demo1.utils;

import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class ListsProgram {

    public static class OneDirListItemIteratorImpl<T> implements Iterator<T> {

        private OneDirListItem<T> item;

        public OneDirListItemIteratorImpl(OneDirListItem<T> item) {
            this.item = item;
        }

        @Override
        public boolean hasNext() {
            return item != null;
        }

        @Override
        public T next() {
            OneDirListItem<T> curr = item;
            item = item.next;
            return curr.val;
        }
    }

    public static class OneDirListItem<T> implements Iterable<T> {
        public T val;
        public OneDirListItem<T> next;

        @Override
        public Iterator<T> iterator() {
            return new OneDirListItemIteratorImpl<>(this);
        }
    }

    public static <T> OneDirListItem<T> makeOneDirList(List<T> items) {
        OneDirListItem<T> curr = new OneDirListItem<>();
        OneDirListItem<T> start = curr;
        OneDirListItem<T> prev = null;
        for (T val : items) {
            curr.val = val;
            curr.next = new OneDirListItem<T>();
            prev = curr;
            curr = curr.next;
        }

        if (prev != null) {
            prev.next = null;
        }

        return start;
    }

    public static void main(String[] args) {
        int lastXNr = 5;
        var l = makeOneDirList(Arrays.asList(10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0));
        var lastXItems = new LinkedList<Integer>();
        for (var el : l) {
            lastXItems.addLast(el);
            if (lastXItems.size() > lastXNr) {
                lastXItems.removeFirst();
            }
        }
        Integer first = lastXItems.getFirst();
        System.out.printf("The last %d element is %d", lastXNr, first);
    }
}
