#  Spellchecker with language detection
#  coding: utf-8
#
#  Copyright © 2008  Santhosh Thottingal
#  Released under the GPLV3+ license

import os
import gtk
import gedit
import enchant
from externaltools.ElementTree import Element


class ISpellcheckPlugin(gedit.Plugin):
 	"""
	A plugin to do the spellcheck on the selected text by detecting the language automatically.
 	"""
	def run_document(self, action, window):
		"""
		Just Do It!
		"""
    	# read in the first line of the buffer...
		buff  = window.get_active_view().get_buffer()
		self.panel = window.get_data("ExternalToolsPluginWindowData")._output_buffer
		try:
			start, end = buff.get_selection_bounds()
		except ValueError:
			start, end = buff.get_bounds()
		text =  buff.get_text(start, end)        
    		if(text):
    			words=text.split()
    			index=0
    			length=len(words)
    			while (index<length):
	    			if(self.check_spelling(words[index])):	
					self.panel.write("Spelling of "+ words[index] + " is Correct\n")
				index=index+1	
		
	def detect_lang(self, word):
		if(word):
			length = len(word)
			index = 0
			while index < length:
				letter=word[index].encode("utf-8")
				if ((letter >= 'ം') &  (letter <= '൯')):
					return "ml_IN"
				if ((letter >= 'ঁ') &  (letter <= '৺')):
					return "bn_IN"
				if ((letter >= 'ँ') &  (letter <= 'ॿ')):
					if((os.getenv('LANG')=='mr_IN') | (os.getenv('LANG')=='mr_IN.utf8')):
						return "mr_IN"
					return "hi_IN"
				if ((letter >= 'ઁ') &  (letter <= '૱')):
					return "gu_IN"
				if ((letter >= 'ਁ') &  (letter <='ੴ')):
					return "pa_IN"
				if ((letter >= 'ಂ') &  (letter <='ೲ')):
					return "ka_IN"
				if ((letter >= 'ଁ') &  (letter <= 'ୱ')):
					return "or_IN"
				if ((letter >= 'ஂ') &  (letter <= '௺')):
					return "ta_IN"
				if ((letter >='ఁ') &  (letter <= '౯')):
					return "te_IN"
				index=index+1	
			return "en_US"

	def check_spelling(self, word):
		if(word):
			self.lang=self.detect_lang(word.decode("utf-8"))
			self.panel.write( "Detected Language: "+ self.lang+"\n")
			try:
				self.dictionary = enchant.Dict(self.lang)
			except enchant.Error:
				self.panel.write( "Dictionary for "+ self.lang  + " not found\n")
				return False
			if  self.dictionary.check(word):
				return True
			else:		
				self.get_suggestions(word)
				return False
				
	def get_suggestions(self, word):
		if(word):
			suggs= self.dictionary. suggest( word)
			length=len(suggs)
			sugg_index=0
			self.panel.write("Spelling of "+ word + " is Incorrect\n")
			self.panel.write("Suggestions\n")
			while (sugg_index<length) :
				self.panel.write(suggs[sugg_index]+"\n")
				sugg_index=sugg_index+1
			  
	def activate(self, window):
		"""
		Setup stuff
		"""
		actions = [
		('RunSpellCheck', gtk.STOCK_EXECUTE, 'Check spelling', 'F10', 'Check spelling', self.run_document),
		]
		# store per window data in the window object
		windowdata = {}
		window.set_data('ISpellcheckPluginWindowDataKey', windowdata)
		windowdata['action_group'] = gtk.ActionGroup('GeditISpellcheckPluginActions')
		windowdata['action_group'].add_actions(actions, window)
		manager = window.get_ui_manager()
		manager.insert_action_group(windowdata['action_group'], -1)
		ui_str = """
		<ui>
			<menubar name="MenuBar">
				<menu name="ToolsMenu" action="Tools">
					<placeholder name="ToolsOps_3">
						<menuitem name="RunSpellCheck" action="RunSpellCheck"/>
							<separator/>
					</placeholder>
				</menu>
			</menubar>
		</ui>
		"""
    		windowdata['ui_id'] = manager.add_ui_from_string(ui_str)
    		window.set_data('ISpellcheckPluginInfo', windowdata)

	def deactivate(self, window):
		"""
		Teardown stuff
		"""
		windowdata = window.get_data('ISpellcheckPluginWindowDataKey')
		manager    = window.get_ui_manager()
		manager.remove_ui(windowdata['ui_id'])
		manager.remove_action_group(windowdata['action_group'])

	def update_ui(self, window):
		"""
		UI Callback
		"""
		view       = window.get_active_view()
		windowdata = window.get_data('ISpellcheckPluginWindowDataKey')
		windowdata['action_group'].set_sensitive(bool(view)) # and view.get_editable()))

