package com.blamejared.mcbot.listeners;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.blamejared.mcbot.util.GuildStorage;
import com.blamejared.mcbot.util.SaveHelper;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import sx.blah.discord.api.events.EventSubscriber;
import sx.blah.discord.handle.impl.events.guild.channel.message.MessageReceivedEvent;

public enum IncrementListener {
    
    INSTANCE;
    
    private static final Pattern PATTERN = Pattern.compile("^(\\S+)(\\+\\+|--)$");
    
    private static final SaveHelper<Map<String, Long>> saveHelper = new SaveHelper<Map<String, Long>>(new File("counts"), new Gson(), new HashMap<>());
    private static final GuildStorage<Map<String, Long>> counts = new GuildStorage<>(
            id -> saveHelper.fromJson(id + ".json", new TypeToken<Map<String, Long>>(){})
    );

    @EventSubscriber
    public void onMessage(MessageReceivedEvent event) {
        String message = event.getMessage().getFormattedContent();
        
        Matcher matcher = PATTERN.matcher(message);
        if (matcher.matches()) {
            String key = matcher.group(1);
            long incr = matcher.group(2).equals("++") ? 1 : -1;
            long current = counts.get(event.getMessage()).merge(key, incr, (a, b) -> a + b);
            event.getChannel().sendMessage(key + " == " + current);
            saveHelper.writeJson(event.getGuild().getLongID() + ".json", counts.get(event.getMessage()));
        }
    }
}

@@ -164,24 +164,81 @@
 x.Pattern;%0A%0A
+import com.blamejared.mcbot.commands.api.CommandContext;%0A
 import com.b
@@ -1488,16 +1488,58 @@
 Message(
+CommandContext.sanitize(event.getGuild(), 
 key + %22 
@@ -1553,16 +1553,17 @@
 current)
+)
 ;%0A      

Sanitize output of incrementation