package org.ccci.gto.android.common.leakcanary;

import android.support.annotation.NonNull;

import com.crashlytics.android.Crashlytics;
import com.squareup.leakcanary.AnalysisResult;
import com.squareup.leakcanary.DisplayLeakService;
import com.squareup.leakcanary.HeapDump;

public class CrashlyticsLeakService extends DisplayLeakService {
    @NonNull
    private static String classSimpleName(@NonNull final String className) {
        int separator = className.lastIndexOf('.');
        return separator == -1 ? className : className.substring(separator + 1);
    }

    protected void afterDefaultHandling(@NonNull final HeapDump heapDump, @NonNull final AnalysisResult result,
                                        @NonNull final String leakInfo) {
        if (!result.leakFound || result.excludedLeak) {
            return;
        }
        Crashlytics.log("*** Memory Leak ***");
        for (final String s : leakInfo.split("\n")) {
            Crashlytics.log(s);
        }
        Crashlytics.log("*** End Of Leak ***");

        String name = classSimpleName(result.className);
        if (!heapDump.referenceName.equals("")) {
            name += "(" + heapDump.referenceName + ")";
        }
        Crashlytics.logException(new Exception(name + " has leaked"));
    }
}

@@ -335,16 +335,69 @@
 rvice %7B%0A
+    private static final int LOG_LIMIT = 64 * 1024;%0A%0A
     @Non
@@ -401,16 +401,16 @@
 NonNull%0A
-
     priv
@@ -775,30 +775,24 @@
    @NonNull 
-final 
 String leakI
@@ -876,32 +876,212 @@
 turn;%0A        %7D%0A
+%0A        // truncate the leakInfo if it's too long for crashlytics%0A        if (leakInfo.length() %3E LOG_LIMIT) %7B%0A            leakInfo = leakInfo.substring(0, LOG_LIMIT);%0A        %7D%0A%0A
         Crashlyt
@@ -1198,16 +1198,16 @@
 log(s);%0A
+
         
@@ -1211,56 +1211,8 @@
    %7D
-%0A        Crashlytics.log(%22*** End Of Leak ***%22);
 %0A%0A  

truncate leak crashlytics log