# encoding: utf-8

require 'pathname'
require 'Win32API'
require 'win32ole'

module Rumix
	def self.base_dir
		if defined?(ExerbRuntime) then
			File.expand_path(File.dirname(ExerbRuntime.filepath))
		else
			Dir.pwd
		end
	end
	
	def self.start_menu_dir_path
		shell = WIN32OLE.new('Wscript.Shell')
		return File.join(shell.SpecialFolders('AllUsersStartMenu'), Uconv.u8tosjis('プログラム/Rumix'))
	end
	
	def self.system_folder_path
		size = 512
		re = "\0" * size
		Win32API.new('kernel32', 'GetSystemDirectory', 'PL', 'L').call(re, size)
		re.delete!("\0")
		
		re
	end
	
	def self.delete_directory_recursively(dir_name, real_operating = false, entries_buffer = [], &block)
		# 配列が渡された場合
		if dir_name.kind_of?(Array) then
			dir_name.each do |real_dir_name|
				delete_directory_recursively(real_dir_name, real_operating, entries_buffer, &block)
			end
			
			return entries_buffer
		end
		
		
	
		path = Pathname.new(dir_name)
		if path.directory? then
			path.children.each do |entry|
				entry = entry.to_s
				if File.directory?(entry) then
					delete_directory_recursively(entry, real_operating, entries_buffer, &block)
					block.call(:directory_ready, entry) if block
					Dir.rmdir(entry) if real_operating
					block.call(:directory, entry) if block
					entries_buffer << entry
				elsif File.file?(entry) then
					block.call(:file_ready, entry) if block
					if real_operating then
						begin
							File.unlink(entry)
						rescue Errno::EACCES
							# 実行中ファイルにアクセスした場合
							if delete_delay_until_reboot(entry) then
								block.call(:delayed_deleting_success, entry) if block
							else
								block.call(:delayed_deleting_failure, entry) if block
							end
						end
					end
					block.call(:file, entry) if block
					entries_buffer << entry
				else
					raise "#{entry} is not file and not directory. (unknown type entry)"
				end
			end
		end
		
		return entries_buffer
	end
	
	def self.delete_delay_until_reboot(path)
		movefile_delay_until_reboot = 4
		
		begin
			api = Win32API.new('kernel32', 'MoveFileEx', %w(p i i), 'i')
		rescue
			return false
		end
						
		ret = api.call("#{path}\0", 0, movefile_delay_until_reboot)
		
		return(ret != 0)
	end

end
