/*
 *  @author Ranides Atterwim <ranides@gmail.com>
 *  @copyright Ranides Atterwim
 *  @license WTFPL
 *  @url http://ranides.net/projects/assira
 */

package net.ranides.assira.text;

import com.google.caliper.SimpleBenchmark;
import net.ranides.assira.BenchmarkRunner;
import net.ranides.assira.math.Randomizer;
import org.apache.commons.lang3.text.StrBuilder;

/**
 *
 * @author ranides
 */
@SuppressWarnings("PMD.AvoidDuplicateLiterals")
public class StringCompilerBenchmark extends SimpleBenchmark {
    
    private final String[] unquoteData;
    private final String[] quoteData;
    
    public StringCompilerBenchmark() {
        
        unquoteData = new String[1000];
        for(int i=0; i<unquoteData.length; i++) {
            if(Randomizer.number(10)>5) {
                unquoteData[i] = StringCompiler.quote(Randomizer.text(128, "qwertyuiopasdfghjklzxcvbnm\"\"\""));
            } else {
                unquoteData[i] = Randomizer.text(128, "qwertyuiopasdfghjklzxcvbnm");
            }
        }
        
        quoteData = new String[1000];
        for(int i=0; i<quoteData.length; i++) {
            if(Randomizer.number(10)>5) {
                quoteData[i] = Randomizer.text(128, "qwertyuiopasdfghjklzxcvbnm\"\"\"");
            } else {
                quoteData[i] = Randomizer.text(128, "qwertyuiopasdfghjklzxcvbnm");
            }
        }
    }
    
    public static String apacheQuote(String value) {
        if (null == value) {
            return "\"\"";
        }
        return "\"" + new StrBuilder(value).replaceAll("\\", "\\\\").replaceAll("\"", "\\\"") + "\"";
    }
    
    public static String apacheUnquote(String value) {
        final String test = StringCompiler.unquoteCheck(value);
        if(null != test) { return test; }

        return new StrBuilder(value.substring(1, value.length()-1) )
            .replaceAll("\\\\", "\\")
            .replaceAll("\\\"", "\"")
            .toString();
    }

    public void timeUnquoteAssira(int reps) {
        for(int r=0; r<reps; r++) {
            for(int i=0, n=unquoteData.length; i<n; i++) {
                StringCompiler.unquote(unquoteData[i]);
            }
        }
    }
    
    public void timeUnquoteApache(int reps) {
        for(int r=0; r<reps; r++) {
            for(int i=0, n=unquoteData.length; i<n; i++) {
                apacheUnquote(unquoteData[i]);
            }
        }
    }
    
    public void timeQuoteAssira(int reps) {
        for(int r=0; r<reps; r++) {
            for(int i=0, n=quoteData.length; i<n; i++) {
                StringCompiler.quote(quoteData[i]);
            }
        }
    }
    
    public void timeQuoteApache(int reps) {
        for(int r=0; r<reps; r++) {
            for(int i=0, n=quoteData.length; i<n; i++) {
                apacheQuote(quoteData[i]);
            }
        }
    }
    
    public static void main(String[] args) throws Exception {
        BenchmarkRunner.run();
    }
}
