require 'darkhall/const'

module DarkHall
	
	module Util
		module_function
		
		
		def convert_key_to_string(src_hash)
			re = {}
			src_hash.each_pair do |key, value|
				re[key.to_s] = value
			end
			
			re
		end
		
		# nilなら表示無し
		def bonus_to_s(value)
			if !(value) then
				'--'
			elsif value > 0 then
				"+#{value}"
			else
				value.to_s
			end
		end

	
		def encrypt(str)
			[str].pack('m')
		end
			
		def decrypt(str)
			str.unpack('m').first
		end
		
		# obsolete
		def random_pick(array)
			array.choice
		end
		
		
		EVAL_TEXT_PATTERN = /%\{(.+?)\}/
		def eval_text(text, params = {})
			re = text.gsub(EVAL_TEXT_PATTERN) do
				params[$1.to_sym] || "(#{$1})"
			end
		
			re
		end
		
		def next_index(index, max)
			index += 1
			index = 0 if index >= max
			return index
		end
		
		def prev_index(index, max)
			index -= 1
			index = (max - 1) if index <= -1
			return index
		end
		
		def fold_in_range(value, range)
			if value > range.last then
				range.last
			elsif value < range.first then
				range.first
			else
				value
			end	
		end
		
		
		
		
		def get_damage_type_caption(damage_types)
			caption = ""
			
			caption << "斬" if damage_types.include?(DT_SLASH)
			caption << "突" if damage_types.include?(DT_THRUST)
			caption << "打" if damage_types.include?(DT_BLOW)
			caption << "熱" if damage_types.include?(DT_HEAT)
			caption << "冷" if damage_types.include?(DT_COLD)
			caption << "雷" if damage_types.include?(DT_ERECTRIC)
			
			caption = "-" if caption.empty?
			
			return caption
		end
		
		def get_damage_resist_caption(resists)
			types = resists.find_all{|k, v| v > RES_NORMAL}.map{|k, v| k}
			return get_damage_type_caption(types)
		end
		
		def get_damage_weakness_caption(resists)
			types = resists.find_all{|k, v| v < RES_NORMAL}.map{|k, v| k}
			return get_damage_type_caption(types)
		end
		
		
	
		
		
		
		
		def targets_caption(targets)
			if targets then
				n_('%{t}', '%{t}たち', targets.size).evaluate(:t => targets.first.name)
			else
				""
			end
	
		end
	end
	
	include Util


	
	
	module Calc
		module_function
	
		# 特性値の算出
		def ability_base(growth, level)
			# 基本値
			re = 8 + growth * 2

			# レベルボーナス
			re += (0.6 + growth * 0.1) * level

			re.to_i
		end
		
		# 防護力→ダメージ減少値
		def def2red(df)
			(df * df * 0.1).round
		end
	end


end


class String
	def evaluate(params)
		DarkHall::Util.eval_text(self, params)
	end
end