package net.mc_pandacraft.java.plugin.pandacraftutils;

import java.util.Set;

import net.mc_pandacraft.java.plugin.pandacraftutils.plugin_interface.EssentialsInterface;
import ru.tehkode.permissions.PermissionUser;
import ru.tehkode.permissions.bukkit.PermissionsEx;

import com.earth2me.essentials.User;
import com.earth2me.essentials.UserMap;

public class PlayerDataCleaner {
	
	private PandacraftUtils plugin;
	
	public PlayerDataCleaner(PandacraftUtils pl) {
		plugin = pl;
		
		
		try {
			clean();
		} catch (Throwable e) {
			e.printStackTrace();
		}
		
		
	}
	
	
	
	private void clean() {
		
		
		String group_to_remove = ConfigManager.getInstance().UsersCleaner_users_cleaner_group;
		
		
		// essentials players
		
		UserMap players = EssentialsInterface.getPlugin().getUserMap();
		plugin.getLogger().info("Group to remove : "+group_to_remove);
		plugin.getLogger().info("Running Essentials players autoremove ..");
		if (players == null) return;
		plugin.getLogger().info("There are "+players.getUniqueUsers()+" players files in Essentials/userdata");
		Set<String> users = players.getAllUniqueUsers();
		
		for (String su : users) {
			User u = players.getUser(su);
			if (u.getBase() != null && u.getBase().isOnline()) continue;
			if (!group_to_remove.equalsIgnoreCase(u.getGroup())) continue;
			plugin.getLogger().info("Essentials players autoremove : "+su);
			players.getUserFile(su).delete();
		}
		players.reloadConfig();
		
		
		// permissions_ex players
		PermissionUser[] pUsers = PermissionsEx.getPermissionManager().getUsers(group_to_remove);
		plugin.getLogger().info("Running PermissionsEx players autoremove ..");
		plugin.getLogger().info("There are "+pUsers.length+" players in 'default' group");
		
		for (PermissionUser pUser : pUsers) {
			if (pUser == null) continue;
			if (pUser.getGroupsNames().length != 1) continue;
			if (!pUser.getGroupsNames()[0].equalsIgnoreCase(group_to_remove)) continue;
			plugin.getLogger().info("PermissionsEx players autoremove : "+pUser.getName());
			pUser.remove();
		}
		PermissionsEx.getPlugin().reloadConfig();
		
		
		
	}
	
	
	
}
