require 'Qt4'
$kxApp = Qt::Application::instance

class KLog < IO
	def initialize
		@receivers = []
	end

	def write(string)
		@receivers.each { |recv| recv.call string }
	end

	def install_receiver(&receiver)
		@receivers << receiver
	end
end

$kxLogger = KLog.new
$kxLogger.install_receiver { |string| qDebug string }

module Kernel
	def kso_load(path)
		load path
	rescue => e
		puts "#{e.class} : #{e.message}"
		KxLogger.writeWarning('ksoruby', "#{e.class} : #{e.message}")
		e.backtrace.each do |xx|
			puts xx
			KxLogger.writeWarning('ksoruby', "#{xx}")
		end
	end

	def puts *args
		args.each { |arg| $kxLogger.write arg.to_s }
		$kxLogger.write "" if args.length == 0
		args
	end

	def p *args
		args.each { |a| $kxLogger.write a.inspect }
		args
	end
end

class KDebugger < Qt::Object
	slots 'onRDebuggerActivated()'
	slots 'onFileDialogActivated()'

	def initialize(parent)
		super(parent)
	end

	def init
		@shortcut = Qt::Shortcut.new Qt::KeySequence.new("Alt+Shift+E"), $kxApp.currentMainWindow, &nil
		connect(@shortcut, SIGNAL('activated()'), self, SLOT('onRDebuggerActivated()'))

		@shortcut2 = Qt::Shortcut.new Qt::KeySequence.new("Alt+Shift+R"), $kxApp.currentMainWindow, &nil
		connect(@shortcut2, SIGNAL('activated()'), self, SLOT('onFileDialogActivated()'))
	end

	def onRDebuggerActivated
		KxUtil.startDebugger
		require_relative 'rdb/rdbg'
		@dbger = RDebugger.new
		@dbger.start
	end

	def onFileDialogActivated
		require 'Qt'
		fileName = Qt::FileDialog::getOpenFileName($kxApp.currentMainWindow, "Open File",
											   "C:",
											   "Ruby files (*.rb *.rbx)")
		kso_load(fileName)
	end
end

def enableDebug?
	path = "#{$kxApp.productVersion}/plugins/officespace/WebDebugger"
	settings = KSettings.new
	settings.value(path, Qt::Variant.new('false')).toBool
end

if enableDebug?
	$kxDebugger = KDebugger.new($kxApp)
	$kxDebugger.init()
end

#kso_plugin

#A66C424DE31262FE7A3BA7F692F31C378E8F4E3714DC2D4C307D91036F13EC18BAFE0825FEB548D394A759292FE4DC6FA65FFC046FC02D789DA92F9235E6439F