package org.innovateuk.ifs.threads.domain;


import org.springframework.data.annotation.CreatedDate;

import javax.persistence.*;
import javax.validation.constraints.Size;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

import static java.util.Optional.empty;
import static java.util.Optional.of;

@Entity
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "thread_type", discriminatorType = DiscriminatorType.STRING)
public abstract class Thread {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private Long classPk;
    private String className;

    @Size(max=255)
    private String title;

    @OneToMany
    private List<Post> posts;

    @CreatedDate
    private LocalDateTime createdOn;


    public final Optional<Post> latestPost() {
        return postAtIndex(numberOfPosts()-1);
    }

    public final Optional<Post> initialPost() {
        return postAtIndex(0);
    }

    private final Optional<Post> postAtIndex(int i) {
        return hasPosts() ? of(posts.get(i)) : empty();
    }

    public final int numberOfPosts() {
        return posts.size();
    }

    public final boolean hasPosts() {
        return !posts.isEmpty();
    }

    public List<Post> posts() {
        return posts;
    }

    public void addPost(Post post) {
        posts.add(post);
    }
}
@@ -197,16 +197,69 @@
 teTime;%0A
+import java.util.ArrayDeque;%0Aimport java.util.Deque;%0A
 import j
@@ -273,16 +273,16 @@
 l.List;%0A
-
 import j
@@ -770,20 +770,26 @@
 private 
-List
+ArrayDeque
 %3CPost%3E p
@@ -917,37 +917,28 @@
 urn 
+of(
 post
-AtIndex(numberOfPo
+s.peekFir
 st
-s
 ()
--1
 );%0A 
@@ -1010,138 +1010,27 @@
 urn 
-postAtIndex(0);%0A    %7D%0A%0A    private final Optional%3CPost%3E postAtIndex(int i) %7B%0A        return hasPosts() ? of(posts.get(i)) : empty(
+of(posts.peekLast()
 );%0A 
@@ -1199,20 +1199,26 @@
  public 
-List
+ArrayDeque
 %3CPost%3E p
@@ -1288,24 +1288,24 @@
 ost post) %7B%0A
-
         post
@@ -1309,16 +1309,21 @@
 osts.add
+First
 (post);%0A

make thread posts list a dequeue to ease the first and last access logic and to keep it ordered by LIFO