package org.black_ixx.bossshop;

import java.util.HashMap;

import org.black_ixx.bossshop.api.BossShopAPI;
import org.black_ixx.bossshop.command.CommandExc;
import org.black_ixx.bossshop.core.BSShopHolder;
import org.black_ixx.bossshop.core.BSShopManager;
import org.black_ixx.bossshop.events.BSReloadedEvent;
import org.black_ixx.bossshop.listeners.InventoryListener;
import org.black_ixx.bossshop.listeners.PlayerListener;
import org.black_ixx.bossshop.listeners.SignListener;
import org.black_ixx.bossshop.lottery.LotteryManager;
import org.black_ixx.bossshop.mail.MailManager;
import org.black_ixx.bossshop.managers.BuyItemHandler;
import org.black_ixx.bossshop.managers.ConfigManager;
import org.black_ixx.bossshop.managers.ItemNameManager;
import org.black_ixx.bossshop.managers.ItemStackCreator;
import org.black_ixx.bossshop.managers.LangManager;
import org.black_ixx.bossshop.managers.MultiplierHandler;
import org.black_ixx.bossshop.managers.RecordManager;
import org.black_ixx.bossshop.managers.ShopCustomizer;
import org.black_ixx.bossshop.managers.TimeHandler;
import org.black_ixx.bossshop.managers.TransactionLog;
import org.black_ixx.bossshop.managers.VaultHandler;
import org.black_ixx.bossshop.managers.WorthHandler;
import org.black_ixx.bossshop.nbt.NBTEditManager;
import org.black_ixx.bossshop.points.PointsManager;
import org.black_ixx.bossshop.sale.SaleListener;
import org.black_ixx.bossshop.sale.SaleManager;
import org.black_ixx.bossshop.util.AttributeRemover;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;

import cc.util.bossshop.FBukkit;
import cc.util.bossshop.config.CommentedYamlConfig;
import cc.util.bossshop.pluginmodel.ABukkitPlugin;
import cc.util.bossshop.pluginmodel.IClearAble;
import cc.util.bossshop.pluginmodel.INeedConfig;
import cc.util.bossshop.pluginmodel.INeedReload;
import me.clip.placeholderapi.PlaceholderAPI;

public class BossShop extends ABukkitPlugin{

    private static BossShop instance;
    public static boolean RE=false;
    private CommandExc mCommander;
    private SaleListener mSaleLis;
    private static long mLastNoticeTime=0;
    private BossShopAPI mAPI;
    @Deprecated
    private final HashMap<Class<?>,Object> mManager=new HashMap<>();

    public BossShop(){
        super("BossShop");
    }

    @Override
    public void onEnable(){
        AttributeRemover.init();
        BossShop.instance=this;
        this.info("开始初始化");
        this.mCommander=new CommandExc(this);
        // 监听器
        new InventoryListener(this);
        new SignListener(this);
        new PlayerListener(this);
        this.mSaleLis=new SaleListener(this);
        new LotteryManager(this);
        this.mAPI=new BossShopAPI(this);

        // 实例化管理器
        this.mConfigManager=new ConfigManager(this);
        this.mManager.put(ConfigManager.class,this.mConfigManager);
        this.mLangManager=new LangManager(this);
        //此处注册管理器模块,注意注册的顺序
        this.registerManager(LangManager.class,this.mLangManager);
        //邮件和商店需要用到NBT,在他们之前注册NBT管理器
        this.registerManager(NBTEditManager.class,new NBTEditManager(this));
        this.registerManager(BSShopManager.class,new BSShopManager(this));
        this.registerManager(MailManager.class,new MailManager(this));
        
        this.registerManager(BuyItemHandler.class,new BuyItemHandler(this));
        this.registerManager(ItemStackCreator.class,new ItemStackCreator(this));
        this.registerManager(MultiplierHandler.class,new MultiplierHandler(this));
        this.registerManager(PointsManager.class,new PointsManager(this));
        this.registerManager(RecordManager.class,new RecordManager(this));
        this.registerManager(SaleManager.class,new SaleManager(this));
        this.registerManager(ShopCustomizer.class,new ShopCustomizer(this));
        this.registerManager(TimeHandler.class,new TimeHandler(this));
        this.registerManager(TransactionLog.class,new TransactionLog(this));
        this.registerManager(VaultHandler.class,new VaultHandler(this));
        this.registerManager(WorthHandler.class,new WorthHandler(this));
        this.registerManager(ItemNameManager.class,new ItemNameManager(this));
        // 载入配置
        this.reloadPlugin();
    }

    @Override
    public void onDisable(){
        for(Player sPlayer : FBukkit.getOnlinePlayers()){
            Inventory inv=sPlayer.getOpenInventory().getTopInventory();
            if(inv.getHolder() instanceof BSShopHolder){
                inv.clear();
                sPlayer.closeInventory();
            }
        }
    }
    
    protected <T> void registerManager(Class<? extends T> clazz,T pManager){
        this.mManager.put(clazz,pManager);
    }

    public <T> T getManager(Class<? extends T> clazz){
        if(clazz==null) return null;
        T tt=null;
        try{
            tt=(T)this.mManager.get(clazz);
        }catch(Exception exp){
            this.severe("获取模块并进行强制转换时发生了错误:"+exp.getMessage(),exp);
            return null;
        }
        if(tt==null) throw new IllegalStateException("管理器类"+clazz.getName()+"没有实例化对象");
        return tt;
    }
    
    public static BossShop getInstance(){
        return (BossShop)mInstance;
    }

    public BossShopAPI getAPI(){
        return this.mAPI;
    }

    public CommandExc getCommandExc(){
        return this.mCommander;
    }

    public ConfigManager getConfigManager(){
        return (ConfigManager)this.mConfigManager;
    }

    public LangManager getLangManager(){
        return (LangManager)this.mLangManager;
    }
    
    public SaleListener getSaleListener(){
        return this.mSaleLis;
    }
    
    @Override
    public void reloadConfig(){
        this.mConfigManager.reloadConfig();
        CommentedYamlConfig tConfig=this.mConfigManager.getConfig();
        this.logpre=ChatColor.translateAlternateColorCodes('&',tConfig.getString("LogPrefix","[BossShop]"));
        this.prefix=ChatColor.translateAlternateColorCodes('&',tConfig.getString("MsgPrefix","§c[§7BossShop§c]§b"));
        for(INeedConfig sConfig : this.mConfigModels)
            sConfig.setConfig();
    }

    public void reloadPlugin(){
        BossShop.isEnablePlaceholderAPI();
        //首先将语言和配置读入,并且模块也读入配置
        this.mLangManager.reloadConfig();
        //主配置的重载
        this.reloadConfig();
        //调用模块的reloadConfig()
        for(INeedReload sReload : this.mReloadModels)
            sReload.reloadConfig();
        
        BSReloadedEvent event=new BSReloadedEvent(this);
        Bukkit.getPluginManager().callEvent(event);
    }

    public int clearMemoryRecord(){
        int count=0;
        for(IClearAble sClearAble : this.mClearModel)
            if(sClearAble.clearStatus()) count++;
        mLastNoticeTime=0;
        return count++;
    }

    /**
     * 替换占位符为实际字符串
     * @param str
     * @return
     */
    public static String replaceParam(Player pPlayer,String pStr){
        if(!BossShop.isEnablePlaceholderAPI()) return ChatColor.translateAlternateColorCodes('&',pStr);
        try{
            pStr=PlaceholderAPI.setPlaceholders(pPlayer,pStr);
        }catch(Throwable exp){
            if(mInstance!=null) mInstance.severe("在调用PlaceHolderAPI是发生了异常,请确保你的插件和PlaceHolderAPI模块版本匹配: "+exp.getMessage(),exp);
        }
        return pStr;
    }

    private static boolean isEnablePlaceholderAPI(){
        if(BossShop.RE) return true;
        if(!Bukkit.getPluginManager().isPluginEnabled("PlaceholderAPI")){
            if(mLastNoticeTime+600000<System.currentTimeMillis()&&mInstance!=null){
                mInstance.info("未发现PlaceholderAPI插件,BossShop插件可能需要该插件来完善功能");
                mInstance.info("请前往https://www.spigotmc.org/resources/placeholderapi.6245 下载");
                mLastNoticeTime=System.currentTimeMillis();
            }
            return false;
        }else{
            BossShop.RE=true;
            return true;
        }
    }
}
