package com.bugsnag.android;

import android.support.annotation.NonNull;

import java.io.IOException;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

class Breadcrumbs implements JsonStream.Streamable {
    private static class Breadcrumb {
        private static final int MAX_MESSAGE_LENGTH = 140;
        final String timestamp;
        final String message;

        Breadcrumb(@NonNull String message) {
            this.timestamp = DateUtils.toISO8601(new Date());
            this.message = message.substring(0, Math.min(message.length(), MAX_MESSAGE_LENGTH));
        }
    }

    private static final int DEFAULT_MAX_SIZE = 20;
    private final List<Breadcrumb> store = new LinkedList<Breadcrumb>();
    private int maxSize = DEFAULT_MAX_SIZE;

    public void toStream(@NonNull JsonStream writer) throws IOException {
        writer.beginArray();

        for (Breadcrumb breadcrumb : store) {
            writer.beginArray();
            writer.value(breadcrumb.timestamp);
            writer.value(breadcrumb.message);
            writer.endArray();
        }

        writer.endArray();
    }

    void add(@NonNull String message) {
        if (store.size() >= maxSize) {
            store.remove(0);
        }

        store.add(new Breadcrumb(message));
    }

    void clear() {
        store.clear();
    }

    void setSize(int size) {
        if (size > store.size()) {
            this.maxSize = size;
        } else {
            store.subList(0, store.size() - size).clear();
        }
    }
}

@@ -135,26 +135,21 @@
 va.util.
-LinkedList
+Queue
 ;%0Aimport
@@ -159,20 +159,48 @@
 va.util.
-List
+concurrent.ConcurrentLinkedQueue
 ;%0A%0Aclass
@@ -699,20 +699,21 @@
 e final 
-List
+Queue
 %3CBreadcr
@@ -733,29 +733,30 @@
 new 
-LinkedList%3CBreadcrumb
+ConcurrentLinkedQueue%3C
 %3E();
@@ -1249,22 +1249,59 @@
     
-store.remove(0
+// Remove oldest breadcrumb%0A            store.poll(
 );%0A 
@@ -1301,33 +1301,32 @@
 ll();%0A        %7D%0A
-%0A
         store.ad
@@ -1539,25 +1539,89 @@
     
-store.subList(0, 
+// Remove oldest breadcrumbs until reaching the required size%0A            while (
 stor
@@ -1633,24 +1633,61 @@
 e() 
--
+%3E
  size)
-.clear();
+ %7B%0A                store.poll();%0A            %7D
 %0A   

Switch breadcrumb store to ConcurrentLinkedQueue to prevent concurrency issues