package com.xwaffle.universalmarket.commands;

import com.xwaffle.universalmarket.UniversalMarket;
import com.xwaffle.universalmarket.market.MarketItem;
import org.spongepowered.api.command.CommandException;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.CommandSource;
import org.spongepowered.api.data.type.HandTypes;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.event.cause.Cause;
import org.spongepowered.api.event.cause.EventContext;
import org.spongepowered.api.item.inventory.ItemStack;
import org.spongepowered.api.service.economy.Currency;
import org.spongepowered.api.service.economy.account.UniqueAccount;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.format.TextColors;

import org.spongepowered.api.item.ItemTypes; // bug fix

import java.math.BigDecimal;

/**
 * Created by Chase(Xwaffle) on 12/18/2017.
 */
public class MarketCommand extends BasicCommand {
    public MarketCommand() {
        super("", "UniversalMarket 主命令", "/universalmarket");
    }

    @Override
    public CommandResult process(CommandSource source, String arguments) throws CommandException {
        String[] args = arguments.split(" ");

        Player player = null;
        if (source instanceof Player) {
            player = (Player) source;
        }

        long expireTime = UniversalMarket.getInstance().getMarket().getExpireTime();
        long totalListings = UniversalMarket.getInstance().getMarket().getTotalItemsCanSell();


        if (arguments.isEmpty() || arguments.equalsIgnoreCase("")) {

            if (player != null) {
                if (player.hasPermission("com.xwaffle.universalmarket.open")) {
                    UniversalMarket.getInstance().getMarket().openMarket(player);
                } else {
                    source.sendMessage(Text.of(TextColors.RED, "你没有权限查看市场"));
                }
            } else {
                source.sendMessage(Text.of(TextColors.RED, "你不能从控制台打开市场"));
            }
            return CommandResult.success();
        }

        if (args.length > 0) {
            switch (args[0].toLowerCase()) {
                case "open":
                case "o":
                    if (player == null)
                        break;
                    if (player.hasPermission("com.xwaffle.universalmarket.open")) {
                        UniversalMarket.getInstance().getMarket().openMarket(player);
                    } else {
                        player.sendMessage(Text.of(TextColors.RED, "你没有权限查看市场"));
                    }
                    break;
                case "add":
                case "a":
                    if (player == null)
                        break;
                    if (!player.hasPermission("com.xwaffle.universalmarket.add")) {
                        player.sendMessage(Text.of(TextColors.RED, "你没有权限上架商品"));
                        return CommandResult.success();
                    }

                    int listingCount = UniversalMarket.getInstance().getMarket().countListings(player.getUniqueId());
                    if (args.length < 2) {
                        player.sendMessage(Text.of(TextColors.RED, "非法的命令！"));
                        player.sendMessage(Text.of(TextColors.YELLOW, "/um " + args[0].toLowerCase() + " (为手中商品所订的价格) (<可选> 数量)"));
                        return CommandResult.success();
                    }

                    if (listingCount >= totalListings) {
                        player.sendMessage(Text.of(TextColors.RED, "你已经达到了一个玩家最多可同时上架的商品数量"));
                        return CommandResult.success();
                    }


                    if (UniversalMarket.getInstance().getMarket().isUsePermissionToSell()) {
                        int userMaxSellPerm = 0;
                        for (int i = 1; i < 99; i++) {
                            if (player.hasPermission("com.xwaffle.universalmarket.addmax." + i)) {
                                userMaxSellPerm = i;
                            }
                        }


                        if (userMaxSellPerm <= listingCount) {
                            player.sendMessage(Text.of(TextColors.RED, "你已经达到了你最多可同时上架的商品数量"));
                            player.sendMessage(Text.of(TextColors.RED, "你最多可以同时上架 ", TextColors.GRAY, userMaxSellPerm, TextColors.RED, " 件商品"));
                            return CommandResult.success();
                        }

                    }


                    // if (player.getItemInHand(HandTypes.MAIN_HAND).isPresent()) {
                    if (player.getItemInHand(HandTypes.MAIN_HAND).isPresent() && player.getItemInHand(HandTypes.MAIN_HAND).get().getType() != ItemTypes.AIR) { // Bug fix
                        ItemStack stack = player.getItemInHand(HandTypes.MAIN_HAND).get();
                        double price;
                        try {
                            price = Double.parseDouble(args[1]);

                            if (price < 0) {
                                player.sendMessage(Text.of(TextColors.RED, "你必须输入一个正数价格！"));
                                return CommandResult.success();

                            }
                        } catch (Exception exc) {
                            player.sendMessage(Text.of(TextColors.RED, "非法的价格"));
                            player.sendMessage(Text.of(TextColors.YELLOW, "/um " + args[0].toLowerCase() + " (为手中商品所订的价格) (<可选> 数量)"));
                            return CommandResult.success();
                        }

                        int amount = stack.getQuantity();

                        if (args.length >= 3) {
                            try {
                                amount = Integer.parseInt(args[2]);
                                if (amount <= 0) {
                                    player.sendMessage(Text.of(TextColors.RED, "你必须输入一个正数数量！"));
                                    return CommandResult.success();
                                } else if (amount > stack.getQuantity()) {
                                    player.sendMessage(Text.of(TextColors.RED, "你不能上架比你手中商品数量还多的商品"));
                                    return CommandResult.success();
                                }
                            } catch (Exception exc) {
                                player.sendMessage(Text.of(TextColors.RED, "非法的数量"));
                                player.sendMessage(Text.of(TextColors.YELLOW, "/um " + args[0].toLowerCase() + " (为手中商品所订的价格) (<可选> 数量)"));
                                return CommandResult.success();
                            }
                        }

                        if (UniversalMarket.getInstance().getMarket().useTax()) {
                            double tax = price * UniversalMarket.getInstance().getMarket().getTax();

                            if (UniversalMarket.getInstance().getEconomyService() == null) {
                                source.sendMessage(Text.of(TextColors.RED, "这个服务器缺乏 UniversalMarket 所必须的经济插件！"));
                                return CommandResult.success();
                            }

                            UniqueAccount account = UniversalMarket.getInstance().getEconomyService().getOrCreateAccount(player.getUniqueId()).get();
                            Currency currency = UniversalMarket.getInstance().getEconomyService().getDefaultCurrency();
                            if (account.getBalance(currency).doubleValue() < tax) {
                                player.sendMessage(Text.of(TextColors.RED, "你无法承受商品上架税！"));
                                player.sendMessage(Text.of(TextColors.RED, "你必须支付商品价格的 ", TextColors.YELLOW, UniversalMarket.getInstance().getMarket().getTax(), TextColors.RED, " 作为商品上架税"));
                                player.sendMessage(Text.of(TextColors.RED, "为了上架商品你需要支付 ", TextColors.GRAY, tax));
                                return CommandResult.success();
                            } else {
                                account.withdraw(currency, new BigDecimal(tax), Cause.of(EventContext.empty(), UniversalMarket.getInstance()));
                                player.sendMessage(Text.of(TextColors.RED, "商品上架税已从你的账户中扣除！"));
                                player.sendMessage(Text.of(TextColors.DARK_RED, "- ", TextColors.RED, tax));
                            }
                        }

                        if (UniversalMarket.getInstance().getMarket().payFlatPrice()) {
                            double flatPrice = UniversalMarket.getInstance().getMarket().getFlatPrice();
                            UniqueAccount account = UniversalMarket.getInstance().getEconomyService().getOrCreateAccount(player.getUniqueId()).get();
                            Currency currency = UniversalMarket.getInstance().getEconomyService().getDefaultCurrency();
                            if (account.getBalance(currency).doubleValue() < flatPrice) {
                                player.sendMessage(Text.of(TextColors.RED, "为了上架商品你需要支付 ", TextColors.GRAY, flatPrice));
                                return CommandResult.success();
                            } else {
                                account.withdraw(currency, new BigDecimal(flatPrice), Cause.of(EventContext.empty(), UniversalMarket.getInstance()));
                                player.sendMessage(Text.of(TextColors.RED, "商品上架费已从你的账户中扣除！"));
                                player.sendMessage(Text.of(TextColors.DARK_RED, "- ", TextColors.RED, flatPrice));
                            }
                        }

                        if (UniversalMarket.getInstance().getMarket().isItemBlacklisted(stack.getType())) {
                            player.sendMessage(Text.of(TextColors.RED, "你不可以上架这个商品 (" + stack.getType().getId() + ")"));
                            return CommandResult.success();
                        }


                        int prevAmount = stack.getQuantity();

                        if (amount == stack.getQuantity()) {
                            player.setItemInHand(HandTypes.MAIN_HAND, null);
                        } else {

                            stack.setQuantity(amount);
                        }


                        int id = UniversalMarket.getInstance().getDatabase().createEntry(stack.copy(), player.getUniqueId(), player.getName(), price, System.currentTimeMillis() + expireTime);
                        UniversalMarket.getInstance().getMarket().addItem(new MarketItem(id, stack.copy(), player.getUniqueId(), player.getName(), price, (System.currentTimeMillis() + expireTime)), false);
                        player.sendMessage(Text.of(TextColors.YELLOW, "商品已经以 ", TextColors.DARK_AQUA, price, TextColors.YELLOW, " 的价格上架到了 UniversalMarket"));

                        if (amount != prevAmount) {
                            stack.setQuantity(prevAmount - amount);
                            player.setItemInHand(HandTypes.MAIN_HAND, stack);
                        }


                    } else {
                        player.sendMessage(Text.of(TextColors.RED, "你需要在你手中拿着你想上架的商品！"));
                    }
                    break;
                case "help":
                case "h":
                case "?":
                    source.sendMessage(Text.of(TextColors.DARK_AQUA, "UniversalMarket 帮助"));
                    source.sendMessage(Text.of(TextColors.YELLOW, "/um or /universalmarket"));
                    source.sendMessage(Text.of(TextColors.YELLOW, "/um a (价格) (<可选> 数量) or /um add (价格) (<可选> 数量)", TextColors.GRAY, " - ", TextColors.GREEN, "上架你手中的商品"));
                    source.sendMessage(Text.of(TextColors.YELLOW, "/um o or /um open", TextColors.GRAY, " - ", TextColors.GREEN, "打开 UniversalMarket"));
                    source.sendMessage(Text.of(TextColors.YELLOW, "/um i or /um info", TextColors.GRAY, " - ", TextColors.GREEN, "显示当前配置"));
                    source.sendMessage(Text.of(TextColors.YELLOW, "/um r or /um reload", TextColors.GRAY, " - ", TextColors.GREEN, "重新加载配置"));
                    break;
                case "reload":
                case "r":
                    if (source.hasPermission("com.xwaffle.universalmarket.reload")) {
                        UniversalMarket.getInstance().getMarket().reloadConfig();
                        source.sendMessage(Text.of(TextColors.GREEN, "配置已经重新加载！（数据库配置修改需要重启服务端后生效）（Xwaffle1 作者 Tollainmear 原始汉化 yys 修复错误 lookas2001 修复错误以及附加汉化）"));
                    } else {
                        source.sendMessage(Text.of(TextColors.RED, "你没有权限重新加载配置"));
                    }
                    break;
                case "info":
                case "i":
                    source.sendMessage(Text.of(TextColors.DARK_AQUA, "当前税率: ", TextColors.AQUA, UniversalMarket.getInstance().getMarket().getTax()));
                    break;
            }
        } else {
            if (player != null) {
                UniversalMarket.getInstance().getMarket().openMarket(player);
            }
        }

        return CommandResult.success();
    }
}
