package org.black_ixx.bossshop.listeners;

import org.black_ixx.bossshop.BossShop;
import org.black_ixx.bossshop.core.BSShopManager;
import org.black_ixx.bossshop.mail.MailManager;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.inventory.ItemStack;

import cc.util.bossshop.config.CommentedYamlConfig;
import cc.util.bossshop.pluginmodel.INeedConfig;

public class PlayerListener implements Listener,INeedConfig{
    
    private BossShop mPlugin;
    private Material mOpenItem=Material.WATCH;
    private boolean mSneakNeed=true;
    
    public PlayerListener(BossShop pPlugin){
        this.mPlugin=pPlugin;
        this.mPlugin.getServer().getPluginManager().registerEvents(this,this.mPlugin);
        this.mPlugin.registerConfigModel(this);
    }
    
    @EventHandler(priority=EventPriority.HIGHEST)
    public void onPlayerInteractItem(PlayerInteractEvent e){
        Player player=e.getPlayer();
        ItemStack item=player.getItemInHand();
        if(item==null||item.getType()==Material.AIR||item.getType()!=this.mOpenItem) return;
        if(!player.hasPermission("BossShop.open.item")) return;
        if(!mSneakNeed||player.isSneaking()){
            e.setCancelled(true);
            this.mPlugin.getManager(BSShopManager.class).openShop(player,this.mPlugin.getConfigManager().getMainShop());
        }
    }
    
    @EventHandler
    public void onPlayerJoin(final PlayerJoinEvent pEvent){
        Bukkit.getScheduler().runTaskLater(this.mPlugin,new Runnable(){
            @Override
            public void run(){
                PlayerListener.this.mPlugin.getManager(MailManager.class).noticeExistMail(pEvent.getPlayer());
            }
        },100);
    }

    @Override
    public void setConfig(){
        CommentedYamlConfig tConfig=this.mPlugin.getConfigManager().getConfig();
        int bind_menn_item=tConfig.getInt("OpenMainShop.BindItem",347);
        this.mOpenItem=Material.getMaterial(bind_menn_item);
        if(this.mOpenItem==null){
            this.mPlugin.warn("绑定打开BossShop主商店的的物品["+bind_menn_item+"]不是一个有效的物品,将设置为默认值的347(钟表)");
            tConfig.set("OpenMainShop.BindItem",347);
            this.mPlugin.getConfigManager().saveConfig();
            this.mOpenItem=Material.WATCH;
        }else this.mPlugin.info("使用"+this.mOpenItem.name()+"作为打开BossShop主商店的的物品");
        this.mSneakNeed=tConfig.getBoolean("OpenMainShop.SneakNeed");
    }

}
