module DarkHall
	
	
	class << Game
		bool_attr_reader :inited, :inited_global_variables, :inited_devices, :inited_data
		attr_reader :gauge_surfaces

		def init
			init_global_variables
			init_devices_and_data
			
			@inited = true
		end
		
		def init_data
			Game.timelog('Data Loading'){
				Dungeon.load_floors
				DB.load
	
				TREASURE_TABLE.setup
				init_shop_lineup
	
				Game.set_room_events
				Game.set_merchant_products
			}
			
			@inited_data = true
			
		end
		
		def init_global_variables
			$troop = Troop.new
			$round = 0
			$member_index = 0
			
			$windows = []
			$selectable_windows = []
			$enemy_windows = []
			$operation_loop_stack = []
			


			GS.clear

			@inited_global_variables = true

		end
		
		def init_shop_lineup
			Game.timelog("item sample set"){
				ITEM_SAMPLES.clear
				ITEM_DATA.each_pair do |str_id, model|
					case model
					when WeaponModel
						cls = Weapon
					when ArmorModel
						cls = Armor
					when AccessoryModel
						cls = Accessory
					when BundleItemModel
						cls = BundleItem
					else
						cls = Item
					end
				
				
					ITEM_SAMPLES[str_id] = cls.new(str_id)
				end
				
				ITEM_SAMPLES['WoodArrow5'] = BundleItem.new('WoodArrow', 5)
				ITEM_SAMPLES['WoodArrow30'] = BundleItem.new('WoodArrow', 30)
				ITEM_SAMPLES['IronArrow5'] = BundleItem.new('IronArrow', 5)
				ITEM_SAMPLES['IronArrow30'] = BundleItem.new('IronArrow', 30)
				#ITEM_SAMPLES['Bolt5'] = BundleItem.new('Bolt', 5)
				#ITEM_SAMPLES['Bolt30'] = BundleItem.new('Bolt', 30)
				
				# 店の標準品揃え
				COMMON_LINEUP.clear
				COMMON_LINEUP[PD_WEAPON] = [:NoviceSword, :Cutlass, :LongSword, :HandAxe, :NoviceSpear, :LongSpear,
				                            :NoviceBow, :LongBow, :NoviceClub, :BoneClub, :MagicianWand].map{|x| x.to_s}
				COMMON_LINEUP[PD_WEAPON].sort!{|a, b| ITEM_SAMPLES[a].price <=> ITEM_SAMPLES[b].price}
				COMMON_LINEUP[PD_WEAPON] += [:WoodArrow5, :WoodArrow30, :IronArrow5, :IronArrow30].map{|x| x.to_s}
																		
				COMMON_LINEUP[PD_ARMOR] = [:NoviceArmor, :LeatherArmor, :BreastPreat, :NoviceCloak, :FeatherCloak].map{|x| x.to_s}
				COMMON_LINEUP[PD_ARMOR] += [:NoviceGuard, :LeatherBuckler, :LargeShield, :ElderGauntlet].map{|x| x.to_s}
		
				COMMON_LINEUP[PD_GOODS] = [:Bandage, :PurifyingWater, :WhiteIncense, :BlackIncense].map{|x| x.to_s}
				
				COMMON_LINEUP[PD_ACCESSORY] = [:ChipOfFlame, :ChipOfThunder, :ChipOfWind, :ChipOfWater, :ChipOfDarkness].map{|x| x.to_s}
				
				COMMON_LINEUP[PD_DEBUG] = [:Sage, :PotionOfVitality, :PotionOfBloodburn, :PotionOfSleep, :SilverDagger, :SteelSword, :Claymore, :ElderBow, :RubyRod, :SapphireRod,
				                           :AmuletOfRedStone, :AmuletOfBlueStone, :AmuletOfWhiteStone, :DProtectRing,
																	 :LastLeaf, :PurifyingGem, :ChainMail, :BlueRibbon, :ThievesCloak, :CompassOfSpell].map{|x| x.to_s}
																	 
				COMMON_LINEUP[PD_DEBUG] = DB.items.find_all{|x| not x.kind_of?(BundleItemModel)}.map{|x| x.id}
																	 
			}
			
			COMMON_LINEUP.each_value do |list|
				list.each do |id|
					raise "item definition not found :#{id}" unless ITEM_SAMPLES[id]
				end
			end

		end
		
		
		def put_loading_texts(texts)
			# 画面初期化
			$screen.fill_rect(0, 0, $screen.w, $screen.h, [ 0, 0, 0 ])
	
			cy = 16
			texts.each do |text|
				Game.regular_ttf.draw_blended_utf8($screen, text, 16, cy, 255, 255, 255)
				cy += (Game.regular_ttf.line_skip + 4)
			end
			put_title
	
			$screen.flip
		end

		
		def init_devices_and_data
		
		
			SDL.init(SDL::INIT_EVERYTHING)
	
			
	
			recommended_bpp = SDL::Screen.info.bpp
			flag = (SETTING.use_hardware_draw? ? SDL::HWSURFACE : SDL::SWSURFACE)
			if ($option_info and $option_info.full_screen) or SETTING.full_screen? then
				flag |= SDL::FULLSCREEN
			end
			
			if Game.debug_mode? then
				$screen = SDL::Screen.open(SCREEN_WIDTH + 240, SCREEN_HEIGHT, recommended_bpp, flag)
				@debug_monitor = DebugMonitor.new
			else
				$screen = SDL::Screen.open(SCREEN_WIDTH, SCREEN_HEIGHT, recommended_bpp, flag)
			end
			
			LOGGER.log(VideoInitializedLog)
			SDL::WM.set_caption(WINDOW_CAPTION, WINDOW_CAPTION)
			
			
		
			
			loading_texts = [_("画面の初期化を完了しました")]
			
			
			loading_texts << _("音楽デバイスを初期化しています...")
			Game.put_loading_texts(loading_texts)
			
			SDL::Mixer.open(SETTING.mixer_frequency, SDL::Mixer::DEFAULT_FORMAT, 2, SETTING.mixer_chunk_size)

			frequency, format, channels = SDL::Mixer.spec
			format_str = case format
			when SDL::Mixer::FORMAT_U8 then "U8"
			when SDL::Mixer::FORMAT_S8 then "S8"
			when SDL::Mixer::FORMAT_U16LSB then "U16LSB"
			when SDL::Mixer::FORMAT_S16LSB then "S16LSB"
			when SDL::Mixer::FORMAT_U16MSB then "U16MSB"
			when SDL::Mixer::FORMAT_S16MSB then "S16MSB"
			else "Unknown"
			end
			
			LOGGER.puts "SDL-Mixer Opened."
			
			LOGGER.puts "  Frequency: #{frequency}"
			LOGGER.puts "  Format: #{format_str}"
			LOGGER.puts "  Channel: #{channels}"
			LOGGER.puts "  Chunk-Size: #{SETTING.mixer_chunk_size}"

		
			Game.timelog('Sound Loading'){
				SE.load
				BGM.load
				LOGGER.info("音楽デバイス初期化成功")
			}
			loading_texts[-1] += _("完了.")
			loading_texts << _("ジョイスティックを初期化しています...")
			Game.put_loading_texts(loading_texts)
		
			# キー初期化
			$joysticks = []
		
			(0...(SDL::Joystick.num)).each do |i|
				$joysticks[i] = SDL::Joystick.open(i)
			end
			LOGGER.log(JoystickInitializedLog)
	
		
			SDL::Key.enable_key_repeat(240, 120)
			
			loading_texts[-1] += _("完了.")
			Game.put_loading_texts(loading_texts)
			
			
			start = 0
			#symbols = [:IronKnife, :LongSword, :ShortBow]
			#symbols.each do |symbol|
			#	FIND_PRODUCT_TABLE[PD_WEAPON].fill(Weapon.new(symbol), start, 4)
			#	start += 4
			#end
			
			
			
			
			
		
		
		
			
			
			
			
			
			#loading_texts.last.concat("完了.")
			loading_texts << _("サーフィスを初期化しています...")
			Game.put_loading_texts(loading_texts)
			
			# 敵グラフィックやHPゲージのサーフェス初期化
			$dark_surface = $screen.display_format_alpha
			$dark_surface.fill_rect(0, 0, 640, 480, [0, 0, 0, 150])
			$enemy_graphic_control.load
			
			@gauge_surfaces = {}
			
			list = [:hp, :hp_small, :exp]
			list.each do |type|
				table = @gauge_surfaces[type] = {}
				table[:base] = Res.load_picture("#{type}.png")
				table[:base] = table[:base].display_format
				
			
				table[:back] = SDL::Surface.new(0, table[:base].w, table[:base].h, $screen)
				table[:back].fill_rect(0, 0, table[:base].w, table[:base].h, [60, 60, 60])
				table[:back] = table[:back].display_format
				
				table[:decrease] = SDL::Surface.new(0, table[:base].w, table[:base].h, $screen)
				table[:decrease].fill_rect(0, 0, table[:base].w, table[:base].h, [100, 40, 40])
				table[:decrease] = table[:decrease].display_format
				
				case type
				when :hp
					table[:warning] = Res.load_picture("#{type}_warning.png")
					table[:warning] = table[:warning].display_format
				else
					table[:warning] = table[:base]
				end
			
			end
			
			PARTY_WINDOW.make_surface.update
			MESSAGE_WINDOW.make_surface(SCREEN_WIDTH - 16*2, 6)
			DESCRIPTION_WINDOW.make_surface
			SEAL_WINDOW.make_surface
			ITEM_DATA_WINDOW.make_surface
		
			
			
			
			
			loading_texts[-1] += _("完了.")
			Game.put_loading_texts(loading_texts)
			
		
			#puts FLOORS[1].area_data.map{|x| x.inspect}
		
			loading_texts << _("データベースファイルを読み込んでいます...")
			Game.put_loading_texts(loading_texts)
			
			Game.init_data
			
			loading_texts[-1] += _("完了.")
			Game.put_loading_texts(loading_texts)

			
		
			
			
			@timer = FPSTimerLight.new(FPS)
			@timer.reset
			LOGGER.info("タイマーを#{FPS}FPSで初期化")
			
			$cursor_alpha = 255
			$cursor_alpha_increasing = false
			
			
			
			
			@inited_devices = true
		end

	end
end
