/*
 * Copyright (c) 2016 Lucko (Luck) <luck@lucko.me>
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a copy
 *  of this software and associated documentation files (the "Software"), to deal
 *  in the Software without restriction, including without limitation the rights
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *  copies of the Software, and to permit persons to whom the Software is
 *  furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in all
 *  copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 *  SOFTWARE.
 */

package me.lucko.luckperms.common.debug;

import lombok.RequiredArgsConstructor;

import com.google.common.collect.ImmutableList;

import me.lucko.luckperms.common.commands.sender.Sender;
import me.lucko.luckperms.common.constants.Message;
import me.lucko.luckperms.common.utils.PasteUtils;
import me.lucko.luckperms.common.utils.Scripting;

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.stream.Collectors;

import javax.script.ScriptEngine;

@RequiredArgsConstructor
public class DebugListener {
    private final String pluginVersion;
    private final Sender holder;
    private final String filter;
    private final boolean notify;

    private List<CheckData> results = new ArrayList<>();

    public void acceptData(CheckData data) {
        if (!matches(data, filter)) {
            return;
        }

        if (results.size() < 500) {
            results.add(data);
        }

        if (notify) {
            Message.LOG.send(holder, "&7Checking &a" + data.getChecked() + "&7 for: &a" + data.getNode() + " &f(&7" + data.getValue().toString() + "&f)");
        }
    }

    private static boolean matches(CheckData data, String filter) {
        if (filter.equals("")) {
            return true;
        }

        ScriptEngine engine = Scripting.getScriptEngine();
        if (engine == null) {
            return false;
        }

        StringTokenizer tokenizer = new StringTokenizer(filter, " |&()", true);
        StringBuilder expression = new StringBuilder();

        while (tokenizer.hasMoreTokens()) {
            String token = tokenizer.nextToken();
            if (!isDelim(token)) {
                boolean b = data.getChecked().equalsIgnoreCase(token) ||
                        data.getNode().toLowerCase().startsWith(token.toLowerCase()) ||
                        data.getValue().name().equalsIgnoreCase(token);

                token = "" + b;
            }

            expression.append(token);
        }

        try {
            String exp = expression.toString().replace("&", "&&").replace("|", "||");
            String result = engine.eval(exp).toString();
            if (!result.equals("true") && !result.equals("false")) {
                throw new IllegalArgumentException(exp + " - " + result);
            }

            return Boolean.parseBoolean(result);

        } catch (Throwable t) {
            t.printStackTrace();
        }

        return false;
    }

    private static boolean isDelim(String token) {
        return token.equals(" ") || token.equals("|") || token.equals("&") || token.equals("(") || token.equals(")");
    }

    public String uploadPastedData() {
        ImmutableList.Builder<String> output = ImmutableList.<String>builder()
                .add("#### This file was automatically generated by [LuckPerms](https://github.com/lucko/LuckPerms) " + pluginVersion)
                .add("")
                .add("Format: `<checked>` `<permission>` `<value>`")
                .add("")
                .add("Size: " + results.size())
                .add("");

        if (results.size() >= 500) {
            output.add("**WARN:** Result set exceeded max size of 500. Output was trimmed.");
            output.add("");
        }

        List<String> ret = results.stream()
                .map(c -> "`" + c.getChecked() + "` - " + c.getNode() + " - **" + c.getValue().toString() + "**   ")
                .collect(Collectors.toList());

        output.add("___")
                .add("")
                .addAll(ret)
                .build();

        results.clear();
        return PasteUtils.paste(output.build().stream().collect(Collectors.joining("\n")));
    }

}

@@ -2613,16 +2613,17 @@
 , %22 %7C&()
+!
 %22, true)
@@ -3777,16 +3777,37 @@
 als(%22)%22)
+ %7C%7C token.equals(%22!%22)
 ;%0A    %7D%0A

Add "!" delimiter to verbose matching