// Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.node.admin.task.util.text;

/**
 * @author hakon
 */
public class SnippetGenerator {

    private static final int ASSUMED_OMIT_TEXT_LENGTH = omitText(1234).length();

    private static String omitText(int omittedLength) { return "[..." + omittedLength + " chars omitted]"; }

    /** Returns a snippet of approximate size. */
    public String makeSnippet(String text, int sizeHint) {
        if (text.length() < sizeHint) return text;

        int maxSuffixLength = Math.max(0, (sizeHint - ASSUMED_OMIT_TEXT_LENGTH) / 2);
        int maxPrefixLength = Math.max(0, sizeHint - ASSUMED_OMIT_TEXT_LENGTH - maxSuffixLength);
        String snippet =
                text.substring(0, maxPrefixLength) +
                omitText(text.length() - maxPrefixLength - maxSuffixLength) +
                text.substring(text.length() - maxSuffixLength);

        // It would be silly to return a snippet when the full text is barely longer.
        // Note: Say ASSUMED_OMIT_TEXT_LENGTH=23: text will be returned whenever sizeHint<23 and text.length()<28.
        if (text.length() <= 1.05 * snippet.length() + 5) return text;

        return snippet;
    }
}

@@ -252,64 +252,36 @@
 nal 
-int ASSUMED_OMIT_TEXT_LENGTH = omitText(1234).length();%0A
+String OMIT_PREFIX = %22%5B...%22;
 %0A   
@@ -300,97 +300,158 @@
 tic 
+final 
 String 
-omitText(int omittedLength) %7B return %22%5B...%22 + omittedL
+OMIT_SUFFIX = %22 chars omitted%5D%22;%0A    private static final int ASSUMED_OMIT_TEXT_LENGTH = OMIT_PREFIX.l
 ength
+()
  + 
-%22 chars omitted%5D%22; %7D
+4 + OMIT_SUFFIX.length();
 %0A%0A  
@@ -584,25 +584,62 @@
 ngth() %3C
- sizeHint
+= Math.max(sizeHint, ASSUMED_OMIT_TEXT_LENGTH)
 ) return
@@ -850,192 +850,68 @@
 ng s
-nippet =%0A                text.substring(0, maxPrefixLength) +%0A                omitText(text.length() - maxPrefixLength - maxSuffixLength) +%0A                text.substring(text.length()
+izeString = Integer.toString(text.length() - maxPrefixLength
  - m
@@ -1129,16 +1129,147 @@
 h()%3C28.%0A
+        int snippetLength = maxPrefixLength + OMIT_PREFIX.length() + sizeString.length() + OMIT_SUFFIX.length() + maxSuffixLength;%0A
         
@@ -1303,25 +1303,22 @@
  snippet
-.l
+L
 ength
-()
  + 5) re
@@ -1344,23 +1344,205 @@
  return 
-snippet
+text.substring(0, maxPrefixLength) +%0A                OMIT_PREFIX +%0A                sizeString +%0A                OMIT_SUFFIX +%0A                text.substring(text.length() - maxSuffixLength)
 ;%0A    %7D%0A

Return earlier if possible in makeSnippet