package org.lockss.plugin.michigan;

import org.lockss.daemon.PluginException;
import org.lockss.filter.FilterUtil;
import org.lockss.plugin.ArchivalUnit;
import org.lockss.rewriter.LinkRewriterFactory;
import org.lockss.servlet.ServletUtil;
import org.lockss.util.LineEndingBufferedReader;
import org.lockss.util.LineRewritingReader;
import org.lockss.util.Logger;
import org.lockss.util.ReaderInputStream;

import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class UMichJavaScriptLinkRewriterFactory implements LinkRewriterFactory {
    static final Logger logger =
            Logger.getLogger(UMichJavaScriptLinkRewriterFactory.class);

    //Modified the patter from the one inside UMichHtmlLinkExtractorFactory, since we need the complete line replacement
    private static final Pattern PATTERN_LEAFLET_TILELAYER_IIIF =  Pattern.compile("(.*tileLayer\\.iiif\\(\")([^?\"]+)(\\?[^\"]*)?(\",.*)");

    public InputStream createLinkRewriter(
            String mimeType, ArchivalUnit au, InputStream in,
            String encoding, final String srcUrl,
            ServletUtil.LinkTransform srvLinkXform)
            throws PluginException, IOException {

        //Need to know how to get base_url here
        final String baseUrl = "https://www.fulcrum.org/";

        LineEndingBufferedReader br = new LineEndingBufferedReader(new InputStreamReader(in));

        Reader filteredReader = FilterUtil.getReader(in, encoding);
        LineRewritingReader rewritingReader = new LineRewritingReader(filteredReader) {
            @Override
            public String rewriteLine(String line) {
                Matcher mat = PATTERN_LEAFLET_TILELAYER_IIIF.matcher(line);

                if (mat.find()) {

                    String replacement = "/ServeContent?url=" + baseUrl.substring(0, baseUrl.length() - 1) + mat.group(2);
                    String replacedScriptLine = line.replaceAll(mat.group(2),replacement);

                    logger.debug3("scrLine is " + srcUrl + ", replaced Line  = " + replacedScriptLine);

                    return replacedScriptLine;
                } else {
                    logger.debug3("No replacement happened  = " + line);
                    return line;
                }
            }
        };
        return new ReaderInputStream(rewritingReader);
    }
}


@@ -1102,16 +1102,22 @@
         
+final 
 ServletU
@@ -1211,105 +1211,94 @@
     
-//Need to know how to get base_url here%0A        final String baseUrl = %22https://www.fulcrum.org/%22
+final String baseUrl = srcUrl.substring(0,(srcUrl.indexOf(%22/concern/file_sets/%22) + 1))
 ;%0A%0A 
@@ -1731,24 +1731,768 @@
 .find()) %7B%0A%0A
+                    String found1 = mat.group(1);%0A                    String found2 = mat.group(2);%0A                    String found3 = mat.group(3);%0A                    String found4 = mat.group(4);%0A%0A                    logger.debug3(%22line = %22 + line + %22 + , #found1 = %22 + found1 + %22, #found2 = %22 + found2 + %22, #found3 = %22 + found3 + %22, #found4 = %22 + found4 + %22#%22);%0A%0A                    //https://www.fulcrum.org/concern/file_sets/7w62f903v?locale=en, replaced Line  =         layer = L.tileLayer.iiif(%22/ServeContent?url=https://www.fulcrum.org/image-service/7w62f903v/info.json?1555623447%22, %7B bestFit: true %7D );%0A                    //http://localhost:8081/ServeContent?url=https://www.fulcrum.org/image-service/7w62f903v/info.json?1555623447%0A
             
@@ -2594,32 +2594,33 @@
 + mat.group(2);%0A
+%0A
                 
@@ -2627,76 +2627,555 @@
     
-String replacedScriptLine = line.replaceAll(mat.group(2),replacement
+//#found2 = /image-service/xg94hq387/info.json#, #found3 = ?1555632458#, #found4 = %22, %7B bestFit: true %7D );#%0A                    //Replace found2 with new link and drop found3, it is the timestamp part%0A                    //use StringBuilder, since replaceAll will give %22Dangling meta character '?' near index 0 %5C%5C?1555623447%22 error%0A                    StringBuilder replacedUrl = new StringBuilder();%0A                    replacedUrl.append(found1);%0A                    replacedUrl.append(replacement);%0A                    replacedUrl.append(found4
 );%0A%0A
@@ -3214,17 +3214,15 @@
 3(%22s
-crLine is
+rcUrl =
  %22 +
@@ -3242,22 +3242,19 @@
 replaced
- Line 
+Url
  = %22 + r
@@ -3264,21 +3264,34 @@
 aced
-ScriptLine);%0A
+Url);%0A                    
 %0A   
@@ -3326,18 +3326,22 @@
 aced
-ScriptLine
+Url.toString()
 ;%0A  

make UMichJavaScriptLinkRewriter get rid of timestamp part of the url