_lcid = 0 # change this if required
from ctypes import *
import comtypes
from comtypes import IUnknown
from comtypes import GUID
from comtypes import COMMETHOD
WSTRING = c_wchar_p
from comtypes import BSTR
from comtypes import CoClass
from comtypes.hresult import *
import logging
logging.basicConfig(level=logging.DEBUG)

class IURLSearchHook(IUnknown):
    _case_insensitive_ = True
    _iid_ = GUID('{AC60F6A0-0FD9-11D0-99CB-00C04FD64497}')
    _idlflags_ = []
class IURLSearchHook2(IURLSearchHook):
    _case_insensitive_ = True
    _iid_ = GUID('{5EE44DA4-6D32-46E3-86BC-07540DEDD0E0}')
    _idlflags_ = []
IURLSearchHook._methods_ = [
    COMMETHOD([], HRESULT, 'Translate',
              ( ['in', 'out'], POINTER(c_wchar), 'lpwszSearchURL' ),
              ( ['in'], c_ulong, 'cchBufferSize' )),
]
class ISearchContext(IUnknown):
    _case_insensitive_ = True
    _iid_ = GUID('{09F656A2-41AF-480C-88F7-16CC0D164615}')
    _idlflags_ = []
IURLSearchHook2._methods_ = [
    COMMETHOD([], HRESULT, 'TranslateWithSearchContext',
              ( ['in', 'out'], POINTER(c_wchar), 'lpwszSearchURL' ),
              ( ['in'], c_ulong, 'cchBufferSize' ),
              ( ['in'], POINTER(ISearchContext), 'pSearchContext' )),
]
ISearchContext._methods_ = [
    COMMETHOD([], HRESULT, 'GetSearchUrl',
              ( ['in'], POINTER(BSTR), 'pbstrSearchUrl' )),
    COMMETHOD([], HRESULT, 'GetSearchText',
              ( ['in'], POINTER(BSTR), 'pbstrSearchText' )),
    COMMETHOD([], HRESULT, 'GetSearchStyle',
              ( ['in'], POINTER(BSTR), 'pdwSearchStyle' )),
]
class AGSearchHook(CoClass):
    u'AGSearchHook Class'
    _reg_clsid_ = GUID('{0BC6E3FA-78EF-4886-842C-5A1258C4455A}')
    _idlflags_ = []
    #_reg_typelib_ = ('{90C026EB-0B99-491A-BD5B-0EB86B533608}', 1, 0)
AGSearchHook._com_interfaces_ = [IURLSearchHook2]


class LILWSearchHook(AGSearchHook):
    
    _reg_threading_ = "Both"
    _reg_progid_ = "AGCoreLib.AGSearchHook.1"
    _reg_novers_progid_ = "AGCoreLib.AGSearchHook"
    _reg_desc_ = ""
    _reg_clsctx_ = comtypes.CLSCTX_INPROC_SERVER

#    def TranslateWithSearchContext(self, lpwszSearchURL, cchBufferSize, pSearchContext):
#        logger.info('Got a search request %s' % lpwszSearchURL)
#        logger.info(type(lpwszSearchURL))
#        logger.info(dir(lpwszSearchURL))
#        
#        #return searchgenerator.GenSearchUrl(lpwszSearchURL)
#        return "http://cnn.com"

    def Translate(self, this, lpwszSearchURL, cchBufferSize):
        # lpwszSearchURL is a POINTER(c_wchar) instance.
        rawdata = lpwszSearchURL[:cchBufferSize]
        # rawdata is now a unicode string of length cchBufferSize, filled with NUL characters
        # at the end.  The [in] unicode string can probably be get by this:
        url = rawdata.split('\0')[0]

        # Maybe ctypes.wstring_at(lpwszSearchURL) would also work.

        # The [out] string must be written into the lpwszSearchURL buffer, maybe this works:
        for i in range(cchBufferSize):
            lpwszSearchURL[i] = '\0'# clear it
        
        urlout = 'http://www.google.com/search?q=%s' % url
        for i in range(len(urlout)):
            if i >= cchBufferSize: break
            lpwszSearchURL[i] = urlout[i]
        return S_OK
    
    def TranslateWithSearchContext(self, this, lpwszSearchURL, cchBufferSize, pSearchContext):
        # lpwszSearchURL is a POINTER(c_wchar) instance.
        rawdata = lpwszSearchURL[:cchBufferSize]
        # rawdata is now a unicode string of length cchBufferSize, filled with NUL characters
        # at the end.  The [in] unicode string can probably be get by this:
        url = rawdata.split('\0')[0]

        # Maybe ctypes.wstring_at(lpwszSearchURL) would also work.

        # The [out] string must be written into the lpwszSearchURL buffer, maybe this works:
        for i in range(cchBufferSize):
            lpwszSearchURL[i] = '\0'# clear it
        
        urlout = 'http://www.google.com/search?q=%s' % url
        for i in range(len(urlout)):
            if i >= cchBufferSize: break
            lpwszSearchURL[i] = urlout[i]
        return S_OK
        
if __name__ == "__main__":
    try:
        from comtypes.server.register import UseCommandLine
##    logging.basicConfig(level=logging.DEBUG)
        UseCommandLine(LILWSearchHook)
    except Exception:
        import traceback
        traceback.print_exc()
 
