package org.black_ixx.bossshop.managers;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import org.apache.commons.lang.StringUtils;
import org.black_ixx.bossshop.BossShop;
import org.black_ixx.bossshop.core.BSBuy;
import org.black_ixx.bossshop.core.BSBuyParameter;
import org.black_ixx.bossshop.core.BSShop;
import org.black_ixx.bossshop.core.BSEnums.BSBuyType;
import org.black_ixx.bossshop.core.BSEnums.BSPriceType;
import org.black_ixx.bossshop.misc.Enchant;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemStack;

/**
 * 用于从商品节点上创建菜单物品和回报物品
 * @author 聪聪
 *
 */
public class BuyItemHandler{

    private BossShop mPlugin;
    private final static SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm");

    
    public BuyItemHandler(BossShop pPlugin){
        this.mPlugin=pPlugin;
    }
    
    private static Date getDate(String str){
        if(str==null) return null;
        Date date=null;
        try{
            date=sdf.parse(str);
        }catch(ParseException pexp){}
        return date;
    }

    @SuppressWarnings({"unchecked","deprecation"})
    public BSBuy createBuyItem(BSShop shop,ConfigurationSection c){
        String stage="Basic Data";
        String name=c.getName();
        ItemStackCreator itemCteator=this.mPlugin.getManager(ItemStackCreator.class);
        try{
            BSBuyParameter parameter=new BSBuyParameter();
            parameter.name=name;
            parameter.shop=shop;
            parameter.msg=c.getString("Message");
            
            if(parameter.weight<0) parameter.weight=0;
            String str_uuid=c.getString("Owner");
            if(str_uuid!=null){
                try{
                    parameter.owner=UUID.fromString(str_uuid);
                }catch(Exception exp){
                    this.mPlugin.severe("配置文件"+shop.getConfigFilename()+"存在错误,["+str_uuid+"]不是一个合法的UUID",exp);
                }
            }
            parameter.hideNoStock=c.getBoolean("HideNoStock",false);
            parameter.hideNotTime=c.getBoolean("HideNotTime",false);
            if(c.contains("HideItemFlag"))
                parameter.hideItemFlag=c.getInt("HideItemFlag");
            else parameter.hideItemFlag=this.mPlugin.getConfigManager().getHideItemFlag();
            parameter.permission=c.getString("ExtraPermission");
            parameter.weight=c.getInt("Weight",0);
            if(StringUtils.isEmpty(parameter.permission)) parameter.permission=null;
            parameter.numberLimit=c.getInt("NumberLimit",-1);
            parameter.personalLimit=c.getInt("PersonalLimit",-1);
            ConfigurationSection time=c.getConfigurationSection("TimeLimit");
            if(time!=null){
                parameter.startTime=BuyItemHandler.getDate(time.getString("start"));
                parameter.stopTime =BuyItemHandler.getDate(time.getString("stop"));
            }
            parameter.location=c.getInt("InventoryLocation")-1;
            if(parameter.location<0){
                parameter.location=0;
                this.mPlugin.warn("商店物品["+name+"]的背包位置["+parameter.location+"]不正确,已经设置为1号位置");
            }
            stage="获取商品类型";
            String rewardType=c.getString("RewardType");
            for(BSBuyType type : BSBuyType.values()){
                if(rewardType.equalsIgnoreCase(type.name())){
                    parameter.buyT=type;
                    break;
                }
            }
            if(parameter.buyT==null){
                this.mPlugin.severe("无法创建商品["+name+"],["+rewardType+"]不是受支持商品类型");
                this.mPlugin.severe("支持的商品类型有");
                for(BSBuyType type : BSBuyType.values()){
                    this.mPlugin.severe("-"+type.name());
                }
                return null;
            }
            stage="获取价格类型";
            String priceType=c.getString("PriceType");
            for(BSPriceType type : BSPriceType.values()){
                if(priceType.equalsIgnoreCase(type.name())){
                    parameter.priceT=type;
                    break;
                }
            }
            if(parameter.priceT==null){
                this.mPlugin.severe("无法创建商品["+name+"],["+priceType+"]不是受支持的价格类型");
                this.mPlugin.severe("支持的价格类型又:");
                for(BSPriceType type : BSPriceType.values()){
                    this.mPlugin.severe("-"+type.name());
                }
                return null;
            }
            parameter.price=c.get("Price");
            parameter.reward=c.get("Reward");
            stage="创建奖励物品";
            switch(parameter.buyT){
            case Item:
                if(!(parameter.reward instanceof List<?>)){
                    this.mPlugin.severe("无法创建商品["+name+"],["+parameter.reward+"]不是List,物品类型的商品必须为List,参见 ( dev.bukkit.org/bukkit-plugins/bossshop/pages/setup-guide/ )");
                    return null;
                }
                List<?> l=(List<?>)parameter.reward;
                boolean b=false;
                for(Object o : l){
                    if(o instanceof List<?>){
                        b=true;
                        break;
                    }
                }
                // Wenn Liste korrekt ist: List<List<String>>
                if(b){
                    List<ItemStack> items=new ArrayList<ItemStack>();
                    for(List<String> s : (List<List<String>>)parameter.reward){
                        items.add(itemCteator.createItemStackS(s,false));
                    }
                    parameter.reward=items;
                }else{
                    // Wenn es eine Liste gibt, in der aber keine weitere Liste
                    // ist
                    List<ItemStack> items=new ArrayList<ItemStack>();
                    items.add(itemCteator.createItemStackS((List<String>)parameter.reward,false));
                    parameter.reward=items;
                }
                break;
            case TimeCommand:
                HashMap<Integer,String> cmds=new HashMap<Integer,String>();
                // Wenn reward = List<String>
                if(parameter.reward instanceof List<?>){
                    for(String s : (List<String>)parameter.reward){
                        try{
                            String[] parts=s.split(":",2);
                            String a1=parts[0].trim();
                            int i=Integer.parseInt(a1);
                            String cmd=parts[1].trim();
                            cmds.put(i,cmd);
                        }catch(Exception e){
                            this.mPlugin.severe("无法创建商品["+name+"],["+s+"]不是一个合法的(TimeCommand),类型商品,正确的格式应该是: <时间>:<命令> 例如 600:ban %name%");
                            return null;
                        }
                    }
                }else{
                    if(!(parameter.reward instanceof String)){
                        this.mPlugin.severe("无法创建商品["+name+"],["+parameter.reward+"]不是一个合法的(TimeCommand)类型商品,正确的格式应该是: <时间>:<命令> 例如 600:ban %name%");
                        return null;
                    }
                    String s=(String)parameter.reward;
                    String[] parts=s.split(":",2);
                    String a1=parts[0].trim();
                    int i=Integer.parseInt(a1);
                    String cmd=parts[1].trim();
                    cmds.put(i,cmd);
                }
                parameter.reward=cmds;
                break;
            case Shop:
                if(parameter.reward instanceof String){
                    String x=(String)parameter.reward;
                    parameter.reward=x.toLowerCase();
                }else{
                    this.mPlugin.severe("无法创建商品["+name+"],["+parameter.reward+"]不是正确的(shop)类型商品");
                    return null;
                }
                break;
            case Command:
                if(!(parameter.reward instanceof List<?>)){
                    if(!(parameter.reward instanceof String)){
                        this.mPlugin.severe("无法创建商品["+name+"],["+parameter.reward+" 不是正确的(Command)类型商品");
                        return null;
                    }
                    List<String> li=new ArrayList<String>();
                    li.add((String)parameter.reward);
                    parameter.reward=li;
                }
                break;
            case PlayerCommand:
                if(!(parameter.reward instanceof List<?>)){
                    if(!(parameter.reward instanceof String)){
                        this.mPlugin.severe("无法创建商品["+name+"! "+parameter.reward+" (PlayerCommand) is no valid Reward list! It needs to be a list of commands!");
                        return null;
                    }
                    List<String> li=new ArrayList<String>();
                    li.add((String)parameter.reward);
                    parameter.reward=li;
                }
                break;
            case Money:
                if(!(parameter.reward instanceof Double)&!(parameter.reward instanceof Integer)){
                    try{
                        parameter.reward=Double.parseDouble((String)(parameter.reward));
                    }catch(Exception exc){
                        this.mPlugin.severe("无法创建商品["+name+"! "+parameter.reward+" (Money) is no valid Reward number!");
                        return null;
                    }
                }
                break;
            case Points:
                if(!(parameter.reward instanceof Integer)){
                    try{
                        parameter.reward=Integer.parseInt((String)(parameter.reward));
                    }catch(Exception exc){
                        this.mPlugin.severe("无法创建商品["+name+"! "+parameter.reward+" (Points) is no valid parameter.reward number!");
                        return null;
                    }
                }
                break;
            case Permission:
                if(!(parameter.reward instanceof List<?>)){
                    if(!(parameter.reward instanceof String)){
                        this.mPlugin.severe("无法创建商品["+name+"! "+parameter.reward+" (Permissions) is no valid parameter.reward list! It needs to be a list of permissions!");
                        return null;
                    }
                    List<String> li=new ArrayList<String>();
                    li.add((String)parameter.reward);
                    parameter.reward=li;
                }
                break;
            case Enchantment:
                if(!(parameter.reward instanceof String)){
                    this.mPlugin.severe("无法创建商品["+name+"! "+parameter.reward+" (Enchantment) is no valid parameter.reward line! It needs to be a text line looking like this: <enchantmenttype/enchantmentid>#<level>!");
                    return null;
                }
                String line=(String)parameter.reward;
                String parts[]=line.split("#",2);
                if(parts.length!=2){
                    this.mPlugin.severe("无法创建商品["+name+"! "+parameter.reward+" (Enchantment) is no valid parameter.reward line! It needs to be a text line looking like this: <enchantmenttype/enchantmentid>#<level>!");
                    return null;
                }
                String p_a=parts[0].trim();
                String p_b=parts[1].trim();
                int lvl=0;
                Enchantment enchantment=null;
                try{
                    lvl=Integer.parseInt(p_b);
                }catch(Exception e){
                    this.mPlugin.severe("无法创建商品["+name+"! "+parameter.reward+" (Enchantment) is no valid parameter.reward line! Invalid level! It needs to be a number!");
                    return null;
                }
                int ench=-1;
                try{
                    ench=Integer.parseInt(p_a);
                }catch(Exception e){}
                if(ench>=0){
                    enchantment=Enchantment.getById(ench);
                }
                if(enchantment==null){
                    enchantment=Enchantment.getByName(p_a);
                }
                if(enchantment==null){
                    this.mPlugin.severe("无法创建商品["+name+"! "+parameter.reward+" (Enchantment) is no valid Reward line! Enchantment not found! Here you can find the right enchantment names: http://jd.bukkit.org/doxygen/db/dbe/namespaceorg_1_1bukkit_1_1enchantments.html");
                    return null;
                }
                parameter.reward=new Enchant(enchantment,lvl);
                break;
            default:
                break;
            }
            stage="创建价格";
            switch(parameter.priceT){
            case Item:
                if(!(parameter.price instanceof List<?>)){
                    this.mPlugin.severe("无法创建商品["+name+"! "+parameter.price+" (Item) is no valid parameter.price Item List! There has to be a list of ItemData ( dev.bukkit.org/bukkit-plugins/bossshop/pages/setup-guide/ )");
                    return null;
                }
                List<?> l=(List<?>)parameter.price;
                boolean b=false;
                for(Object o : l){
                    if(o instanceof List<?>){
                        b=true;
                    }
                }
                // Wenn Liste korrekt ist: List<List<String>>
                if(b){
                    List<ItemStack> items=new ArrayList<ItemStack>();
                    for(List<String> s : (List<List<String>>)parameter.price){
                        items.add(itemCteator.createItemStackS(s,false));
                    }
                    parameter.price=items;
                }else{
                    // Wenn es eine Liste gibt, in der aber keine weitere Liste
                    // ist
                    List<ItemStack> items=new ArrayList<ItemStack>();
                    items.add(itemCteator.createItemStackS((List<String>)parameter.price,false));
                    parameter.price=items;
                }
                break;
            case Free:
                break;
            case Nothing:
                break;
            case Exp:
                if(!(parameter.price instanceof Integer)){
                    try{
                        parameter.price=Integer.parseInt((String)(parameter.price));
                    }catch(Exception exc){
                        this.mPlugin.severe("无法创建商品["+name+"! "+parameter.price+" (Exp) is no valid parameter.price number!");
                        return null;
                    }
                }
                break;
            case Money:
                if(!(parameter.price instanceof Double)&!(parameter.price instanceof Integer)){
                    try{
                        parameter.price=Double.parseDouble((String)(parameter.price));
                    }catch(Exception exc){
                        this.mPlugin.severe("无法创建商品["+name+"! "+parameter.price+" (Money) is no valid parameter.price number!");
                        return null;
                    }
                }
                break;
            case Points:
                if(!(parameter.price instanceof Integer)){
                    try{
                        parameter.price=Integer.parseInt((String)(parameter.price));
                    }catch(Exception exp){
                        this.mPlugin.severe("无法创建商品["+name+"! "+parameter.price+" (Points) is no valid parameter.price number!");
                        return null;
                    }
                }
                break;
            }
            return new BSBuy(this.mPlugin,parameter);
        }catch(Throwable exp){
            this.mPlugin.severe("无法创建商品 "+name+"! 在步骤 '"+stage+"',可能是由于错误的插件配置",exp);
            return null;
        }
    }

    
}
