package org.gestern.gringotts.dependency;

import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.gestern.gringotts.Gringotts;
import org.gestern.gringotts.accountholder.AccountHolder;
import org.gestern.gringotts.accountholder.AccountHolderProvider;
import org.gestern.gringotts.event.PlayerVaultCreationEvent;

import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.domains.DefaultDomain;
import com.sk89q.worldguard.protection.GlobalRegionManager;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;

public class WorldGuardHandler implements DependencyHandler, AccountHolderProvider {

    private final WorldGuardPlugin plugin;

    public WorldGuardHandler(WorldGuardPlugin plugin) {
        this.plugin = plugin;

        Bukkit.getPluginManager().registerEvents(new WorldGuardListener(), Gringotts.G);
        Gringotts.G.registerAccountHolderProvider("worldguard", this);
    }

    @Override
    public boolean enabled() {
        return plugin.isEnabled();
    }

    @Override
    public boolean exists() {
        return plugin != null;
    }


    @Override
    public WorldGuardAccountHolder getAccountHolder(String id) {
        GlobalRegionManager manager = plugin.getGlobalRegionManager();
        for (World world: Bukkit.getWorlds()) {
            RegionManager worldManager = manager.get(world);
            if (worldManager.hasRegion(id)) {
                ProtectedRegion region = worldManager.getRegion(id);
                return new WorldGuardAccountHolder(world.getName(), region);
            }

        }

        return null;
    }

    /**
     * Get account holder for known world and region id/
     * @param world
     * @param id
     * @return
     */
    public WorldGuardAccountHolder getAccountHolder(String world, String id) {
        World w = Bukkit.getWorld(world);
        if (w == null) return null;
        RegionManager manager = plugin.getRegionManager(w);
        if (manager == null) return null;

        if (manager.hasRegion(id)) {
            ProtectedRegion region = manager.getRegion(id);
            return new WorldGuardAccountHolder(world, region);
        }

        return null;
    }

    public class WorldGuardListener implements Listener {

        @EventHandler
        public void vaultCreated(PlayerVaultCreationEvent event) {
            // some listener already claimed this event
            if (event.isValid()) return;

            if (event.getType().equals("region")) {
                Player player = event.getCause().getPlayer();
                String regionId = event.getCause().getLine(2);
                String[] regionComponents = regionId.split("-",1);

                WorldGuardAccountHolder owner = null;
                if (regionComponents.length == 1) {
                    // try to guess the world
                    owner = getAccountHolder(regionComponents[0]);
                } else {
                    String world = regionComponents[0];
                    String id = regionComponents[1];
                    owner = getAccountHolder(world, id);
                }


                if (owner != null && owner.region.hasMembersOrOwners()) {
                    DefaultDomain regionOwners = owner.region.getOwners();
                    if (regionOwners.contains(player.getName())) {
                        event.setOwner(owner);
                        event.setValid(true);
                    }
                }
            }
        }
    }

    public static class WorldGuardAccountHolder implements AccountHolder {

        private final String world;
        private final ProtectedRegion region;

        public WorldGuardAccountHolder(String world, ProtectedRegion region) {
            this.world = world;
            this.region = region;
        }

        @Override
        public String getName() {
            return region.getId();
        }

        @Override
        public void sendMessage(String message) {
            // TODO send message to all memebers?
        }

        @Override
        public String getType() {
            return "worldguard";
        }

        @Override
        public String getId() {
            return world+"-"+region.getId();
        }

    }
}

@@ -1335,32 +1335,392 @@
 er(String id) %7B%0A
+        // FIXME use something more robust than - as world-id delimiter%0A        // try explicit world+id first %0A        String%5B%5D parts = id.split(%22-%22, 2);%0A        if (parts.length == 2) %7B%0A            WorldGuardAccountHolder wgah = getAccountHolder(parts%5B0%5D, parts%5B1%5D);%0A            if (wgah != null) return wgah;%0A        %7D%0A%0A        // try bare id in all worlds%0A
         GlobalRe
@@ -1770,24 +1770,24 @@
 nManager();%0A
-
         for 
@@ -2081,33 +2081,32 @@
 ;%0A            %7D%0A
-%0A
         %7D%0A%0A     
@@ -2191,17 +2191,17 @@
 egion id
-/
+.
 %0A     * 

make world guard accountholder provider more robust