/**
 * Copyright 2008-2009. Chongqing Communications Industry Services Co.,Ltd Information Technology Branch. All rights reserved.
 * <a>http://www.crunii.com</a>
 */
package com.crunii.micro.common.concurrent.collection.impl;

import com.crunii.micro.common.concurrent.collection.FixSizeList;
import com.crunii.micro.common.concurrent.collection.RemoveId;
import org.springframework.util.Assert;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * <pre>
 *     写多读少直接全部同步方法
 * </pre>
 *
 * @author 田平 create 2022-07-27 14:06:56
 */
public class FixSizeLinkedList<T extends Serializable & RemoveId> implements FixSizeList<T> {

	private LinkedList<T> list;
	private int size;

	public FixSizeLinkedList(int size) {
		this.size = size;
		list = new LinkedList<>();
		Assert.isTrue(size > 0, "size must be more than zero!");
	}

	@Override
	public synchronized List<T> getAll() {
		return new ArrayList<>(list);
	}

	@Override
	public synchronized void add(T element) {
		list.add(element);
		if (list.size() > size) {
			list.removeFirst();
		}
	}

	@Override
	public synchronized void addAll(List<T> elements) {
		list.addAll(elements);
		int remove = list.size() - size;
		if (remove > 0) {
			for (int i = 0; i < remove; i++) {
				list.removeFirst();
			}
		}
	}

	@Override
	public synchronized void clear() {
		list.clear();
	}

	@Override
	public synchronized boolean removeById(String removeId) {
		return list.removeIf(t -> t.getRemoveId().equals(removeId));
	}

	public static void main(String[] args) {
		FixSizeLinkedList<SimpleRemoveId> fix = new FixSizeLinkedList(5);
		for (int i = 0; i < 10; i++) {
			fix.add(new SimpleRemoveId(String.valueOf(i)));
		}
		System.out.println(fix.removeById("5100"));
		System.out.println(fix.removeById("7100"));
		fix.getAll().forEach(System.out::println);
	}
}
