package com.github.games647.scoreboardstats.variables.defaults;

import com.github.games647.scoreboardstats.variables.ReplaceEvent;
import com.google.common.collect.Sets;
import com.google.common.primitives.Doubles;

import java.util.Collection;
import java.util.Set;

import me.clip.placeholderapi.PlaceholderAPI;
import me.clip.placeholderapi.PlaceholderHook;
import me.clip.placeholderapi.expansion.PlaceholderExpansion;
import me.clip.placeholderapi.external.EZPlaceholderHook;

import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;

public class PlaceHolderVariables extends DefaultReplaceAdapter<Plugin> {
    
    private static String[] getVariablesPrefixes() {
        Set<String> variables = Sets.newHashSet();

        Collection<PlaceholderHook> hooks = PlaceholderAPI.getPlaceholders().values();
        for (PlaceholderHook hook : hooks) {
            String variablePrefix = null;
            if (hook instanceof EZPlaceholderHook) {
                variablePrefix = ((EZPlaceholderHook) hook).getPlaceholderName();
            } else if (hook instanceof PlaceholderExpansion) {
                variablePrefix = ((PlaceholderExpansion) hook).getIdentifier();
            }

            if (variablePrefix != null) {
                variables.add(variablePrefix + "_*");
            }
        }

        return variables.stream().toArray(String[]::new);
    }

    public PlaceHolderVariables() {
        super(Bukkit.getPluginManager().getPlugin("PlaceholderAPI"), getVariablesPrefixes());
    }

    @Override
    public void onReplace(Player player, String variable, ReplaceEvent replaceEvent) {
        String replaced = PlaceholderAPI.setPlaceholders(player, '%' + variable + '%');
        //remove colors if inserted by the replace plugin
        String strip = ChatColor.stripColor(replaced);
        
        //try parse with a decimal in the case it's decimal if not it parsing will work too
        Double score = Doubles.tryParse(strip);
        if (score != null) {
            //is not text variable and so this could be parsed to a number
            replaceEvent.setScoreOrText(score.intValue());
        }
    }
}

@@ -167,53 +167,8 @@
 ets;
-%0Aimport com.google.common.primitives.Doubles;
 %0A%0Aim
@@ -431,16 +431,65 @@
 rHook;%0A%0A
+import org.apache.commons.lang.math.NumberUtils;%0A
 import o
@@ -1987,17 +1987,17 @@
         
-D
+d
 ouble sc
@@ -2006,141 +2006,37 @@
 e = 
-Doubles.tryParse(strip);%0A        if (score != null) %7B%0A            //is not text variable and so this could be parsed to a number%0A    
+NumberUtils.toDouble(strip);%0A
     
@@ -2071,36 +2071,21 @@
 ext(
-score.intValue());%0A        %7D
+(int) score);
 %0A   

Fix number parsing because of old Guava version in MCPC (Related #153)