# Currency created by IsCoelho
# @author Coelho <robertcoelho@live.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.

Plugin.is {
	name "CurrencyBasic"
	version "0.3"
	author	"Coelho"
	description "Basic commands for the CurrencyCore economy plugin"
	commands :currency => {
		:description => "",
		:usage => "/currency (action) [parameters]",
		:aliases => [ :econ, :economy, :money, :cash ]
	}
}

import 'org.bukkit.ChatColor'

class CurrencyBasic < RubyPlugin

	def initialize
		@colors = {
		'&1' => ChatColor::DARK_BLUE,
                '&2' => ChatColor::DARK_GREEN,
                '&3' => ChatColor::DARK_AQUA,
                '&4' => ChatColor::DARK_RED,
                '&5' => ChatColor::DARK_PURPLE,
                '&6' => ChatColor::GOLD,
                '&7' => ChatColor::GRAY,
                '&8' => ChatColor::DARK_GRAY,
                '&9' => ChatColor::BLUE,
                '&a' => ChatColor::GREEN,
                '&b' => ChatColor::AQUA,
                '&c' => ChatColor::RED,
                '&d' => ChatColor::LIGHT_PURPLE,
                '&e' => ChatColor::YELLOW,
                '&f' => ChatColor::WHITE
		}
		@messages = {
		:balance => "&7[&fCurrency&7] &cBalance: &3%s",
		:balance_other => '&7[&fCurrency&7] &3%s\'s &cBalance: &3%s',
		:balance_invalid_account => '&7[&fCurrency&7] &cAccount &3%s &cdoes not exist',
		:version => "&7[&fCurrency&7] &3%s &cauthored by &3%s",
		:send => "&7[&fCurrency&7] &3%s &csent to &3%s",
		:send_receive => "&7[&fCurrency&7] &3%s &creceived from &3%s",
		:send_no_account => "&7[&fCurrency&7] &cAccount not specified. &3/currency send [account] [amount]",
		:send_invalid_account => "&7[&fCurrency&7] &cAccount &3%s &cdoes not exist",
		:send_no_amount => "&7[&fCurrency&7] &cAmount not specified. &3/currency send [account] [amount]",
		:send_invalid_amount => "&7[&fCurrency&7] &cAmount must be a non-negative decimal",
		:sent_insufficient_funds => "&7[&fCurrency&7] &cAmount &3%s &cis too high for your balance.",
		:create => "&7[&fCurrency&7] &3%s's &caccount created",
		:create_no_account => "&7[&fCurrency&7] &cAccount not specified. &3/currency create [account]",
		:create_invalid_account => "&7[&fCurrency&7] &cAccount &3%s &calready exists",
		:delete => "&7[&fCurrency&7] &3%s's &caccount deleted",
		:delete_no_account => "&7[&fCurrency&7] &cAccount not specified. &3/currency delete [account]",
		:delete_invalid_account => "&7[&fCurrency&7] &cAccount &3%s &cdoes not exist",
		:grant => "&7[&fCurrency&7] &3%s &cgranted to &3%s",
		:grant_receive => "&7[&fCurrency&7] &3%s &cgranted from &3%s",
		:grant_no_account => "&7[&fCurrency&7] &cAccount not specified. &3/currency grant [account] [amount]",
		:grant_invalid_account => "&7[&fCurrency&7] &cAccount &3%s &cdoes not exist",
		:grant_no_amount => "&7[&fCurrency&7] &cAmount not specified. &3/currency grant [account] [amount]",
		:set => "&7[&fCurrency&7] &3%s's &cbalance set to &3%s",
                :set_receive => "&7[&fCurrency&7] &cBalance set to &3%s &cby &3%s",
                :set_no_account => "&7[&fCurrency&7] &cAccount not specified. &3/currency grant [account] [amount]",
                :set_invalid_account => "&7[&fCurrency&7] &cAccount &3%s &cdoes not exist",
                :set_no_amount => "&7[&fCurrency&7] &cAmount not specified. &3/currency grant [account] [amount]",
		:stats => "&cCurrency Statistics",
		:stats_entry => "&7%s&c: &3%s",
		:help => "&cCurrencyBasic Help", 
		:help_entry => "&7%s&c: &3%s",
		:error_no_command => "&7[&fCurrency&7] &cCommand not specified. Type &3/currency help &cfor help.",
		:error_invalid_command => "&7[&fCurrency&7] &cCommand invalid: &3%s&c. Type &3/currency help &cfor help."
		}
	end

	def onEnable
		@currency = getServer.getPluginManager.getPlugin "CurrencyCore"
		print getDescription.getFullName + " authored by " + getDescription.getAuthors.toString + " enabled."
	end

	def onDisable
		print getDescription.getFullName + " disabled."
	end

	def onCommand(sender, command, label, args)
		if args.length == 0
			if sender.isPlayer && hasPermission(sender, "currencybasic.balance")
				sender.sendMessage colorize(@messages[:balance] % format(getAccount(sender.getName).getBalance))
			else
				sender.sendMessage colorize(@messages[:error_no_command])
			end
		elsif (hasPermission(sender, "currencybasic.balance") && args.length == 1 || hasPermission(sender, "currencybasic.balance.other")) && (args[0].casecmp("bal") == 0 || args[0].casecmp("balance") == 0) 
			if args.length == 1
				sender.sendMessage colorize(@messages[:balance] % format(getAccount(sender.getName).getBalance))
			else
				if !hasAccount args[1]
					sender.sendMessage colorize(@messages[:balance_invalid_account] % args[1])
				else
					sender.sendMessage colorize(@messages[:balance_other] % [args[1], format(getAccount(sender.getName).getBalance)])
				end
			end
		elsif hasPermission(sender, "currencybasic.send") && args[0].casecmp("send") == 0
			if args.length == 1
				sender.sendMessage colorize(@messages[:send_no_account])
			else
				if args.length == 2
					sender.sendMessage colorize(@messages[:send_no_amount])
				else
					if !hasAccount args[1]
						sender.sendMessage colorize(@messages[:send_invalid_account] % args[1])
					else
						amount = args[2].to_f;
						if amount < 0
							sender.sendMessage colorize(@messages[:send_invalid_amount])
						else
							if !getAccount(sender.getName).hasBalance amount
								sender.sendMessage colorize(@messages[:sent_insufficient_funds] % format(amount))
							else
								getAccount(sender.getName).subtractBalance amount
								getAccount(args[1]).addBalance amount

								sender.sendMessage colorize(@messages[:send] % [format(amount), args[1]])
								receiver = getServer.getPlayer(args[1])
								if receiver != nil
									receiver.sendMessage colorize(@messages[:send_receive] % [format(amount), sender.getName])
								end
							end
						end
					end
				end
			end
		elsif hasPermission(sender, "currencybasic.create") && args[0].casecmp("create") == 0
			if args.length == 1
				sender.sendMessage colorize(@messages[:create_no_account])			
			else
				if hasAccount args[1]
					sender.sendMessage colorize(@messages[:create_invalid_account] % args[1])				
				else
					createAccount args[1]
					sender.sendMessage colorize(@messages[:create] % args[1])
				end
			end
		elsif hasPermission(sender, "currencybasic.delete") && args[0].casecmp("delete") == 0
			if args.length == 1
				sender.sendMessage colorize(@messages[:delete_no_account])			
			else
				if !hasAccount args[1]
					sender.sendMessage colorize(@messages[:delete_invalid_account] % args[1])				
				else
					deleteAccount args[1]
					sender.sendMessage colorize(@messages[:delete] % args[1])
				end
			end
		elsif hasPermission(sender, "currencybasic.set") && args[0].casecmp("set") == 0
			if args.length == 1
                                sender.sendMessage colorize(@messages[:set_no_account])
                        else
                                if args.length == 2
                                        sender.sendMessage colorize(@messages[:set_no_amount])
                                else
                                        if !hasAccount args[1]
                                                sender.sendMessage colorize(@messages[:set_invalid_account] % args[1])
                                        else
                                                amount = args[2].to_f
                                                getAccount(args[1]).setBalance amount

                                                sender.sendMessage colorize(@messages[:set] % [args[1], format(amount)]) 
                                                receiver = getServer.getPlayer(args[1]) 
                                                if receiver != nil
                                                        receiver.sendMessage colorize(@messages[:set_receive] % [format(amount), sender.getName])
                                                end
                                        end
                                end
                        end
		elsif hasPermission(sender, "currencybasic.grant") && args[0].casecmp("grant") == 0
			if args.length == 1
				sender.sendMessage colorize(@messages[:grant_no_account])
			else
				if args.length == 2
					sender.sendMessage colorize(@messages[:grant_no_amount])
				else
					if !hasAccount args[1]
						sender.sendMessage colorize(@messages[:grant_invalid_account] % args[1])
					else
						amount = args[2].to_f
						getAccount(args[1]).addBalance amount

						sender.sendMessage colorize(@messages[:grant] % [format(amount), args[1]])
						receiver = getServer.getPlayer(args[1])
						if receiver != nil
							receiver.sendMessage colorize(@messages[:grant_receive] % [format(amount), sender.getName])
						end
					end
				end
			end
		elsif hasPermission(sender, "currencybasic.stats") && args[0].casecmp("stats") == 0
			totalBalance = 0.0
			highestBalance = 0.0
			highestBalanceAccount = 0.0
			highestBalanceSet = false
			lowestBalance = 0.0
			lowestBalanceAccount = 0.0
			lowestBalanceSet = false
			getAccounts.each do |username|
				account = getAccount username
				accountBalance = account.getBalance
				accountUsername = account.getUsername
				totalBalance += accountBalance
				if highestBalanceSet == false || highestBalance < accountBalance
					highestBalance = accountBalance
					highestBalanceAccount = accountUsername
					highestBalanceSet = true
				end
				if lowestBalanceSet == false || lowestBalance > accountBalance
					lowestBalance = accountBalance
					lowestBalanceAccount = accountUsername
					lowestBalanceSet = true
				end
			end

			sender.sendMessage colorize(@messages[:stats])
			sender.sendMessage colorize(@messages[:stats_entry] % ["Total Balance", format(totalBalance)])
			sender.sendMessage colorize(@messages[:stats_entry] % ["Highest Balance", format(highestBalance) + " from " + highestBalanceAccount])
			sender.sendMessage colorize(@messages[:stats_entry] % ["Lowest Balance", format(lowestBalance) + " from " + lowestBalanceAccount])
		elsif hasPermission(sender, "currencybasic.help") && args[0].casecmp("help") == 0
			sender.sendMessage colorize(@messages[:help])
			sender.sendMessage colorize(@messages[:help_entry] % ["/currency", "Alias /currency balance"])
			sender.sendMessage colorize(@messages[:help_entry] % ["/currency help", "Display help"])
			sender.sendMessage colorize(@messages[:help_entry] % ["/currency balance (account)", "Check account balance"])
			sender.sendMessage colorize(@messages[:help_entry] % ["/currency send [account] [amount]", "Send currency"])
			sender.sendMessage colorize(@messages[:help_entry] % ["/currency create [account]", "Create account"])
			sender.sendMessage colorize(@messages[:help_entry] % ["/currency delete [account]", "Delete account"])
			sender.sendMessage colorize(@messages[:help_entry] % ["/currency set [account] [amount]", "Set account balance"])
			sender.sendMessage colorize(@messages[:help_entry] % ["/currency grant [account] [amount]", "Grant account currency"])
			sender.sendMessage colorize(@messages[:help_entry] % ["/currency stats", "Display statistics"])
			sender.sendMessage colorize(@messages[:help_entry] % ["/currency version", "Display version"])
		elsif args[0].casecmp("v") == 0 || args[0].casecmp("version") == 0
			sender.sendMessage colorize(@messages[:version] % [getDescription.getFullName, getDescription.getAuthors.toString])
			sender.sendMessage colorize(@messages[:version] % [@currency.getDescription.getFullName, @currency.getDescription.getAuthors.toString])
		else
			sender.sendMessage colorize(@messages[:error_invalid_command] % args[0])
		end
		return true
	end

	def format(amount)
		return @currency.getFormatHelper.format amount
	end

	def createAccount(username)
		@currency.getAccountManager.createAccount username
	end

	def deleteAccount(username)
		@currency.getAccountManager.removeAccount username
	end
	
	def getAccount(username)
		return @currency.getAccountManager.getAccount username
	end

	def getAccounts
		return @currency.getAccountManager.getAccounts
	end

	def hasAccount(username)
		return @currency.getAccountManager.hasAccount username
	end

	def hasPermission(sender, node)
		begin
			if sender.hasPermission node
				return true
			end
		rescue
			return sender.isOp
		end
		return false
	end

	def colorize(s)
	        @colors.each do|i,v| 
	            s = s.gsub(i, v.to_s)
	        end
		return s
    	end

end
