#! /usr/bin/env python2

# https://gist.github.com/scottgwald/6862517
# from http://stackoverflow.com/questions/11524586/accessing-logcat-from-android-via-python
import Queue
import subprocess
import threading
import datetime

import re

from pymouse import PyMouse

class AsynchronousFileReader(threading.Thread):
    '''
    Helper class to implement asynchronous reading of a file
    in a separate thread. Pushes read lines on a queue to
    be consumed in another thread.
    '''

    def __init__(self, fd, queue):
        assert isinstance(queue, Queue.Queue)
        assert callable(fd.readline)
        threading.Thread.__init__(self)
        self._fd = fd
        self._queue = queue

    def run(self):
        '''The body of the thread: read lines and put them on the queue.'''
        for line in iter(self._fd.readline, ''):
            self._queue.put(line)

    def eof(self):
        '''Check whether there is no more content to expect.'''
        return not self.is_alive() and self._queue.empty()

process = subprocess.Popen(['adb', 'logcat'], stdout=subprocess.PIPE)

stdout_queue = Queue.Queue()
stdout_reader = AsynchronousFileReader(process.stdout, stdout_queue)
stdout_reader.start()

mouse = PyMouse()

# XXX: picking up the time-related info because at some point it would make
# sense to ignore past events -- not implemented yet though
line_re = \
  re.compile("^(\d+)-(\d+) (\d+):(\d+):(\d+)\.(\d+)\s+.*" +
             ":\s+ev_p:\s+(?P<x>\d+),(?P<y>\d+)\s.*")

try:
    while not stdout_reader.eof():
        while not stdout_queue.empty():
            line = stdout_queue.get()
            m = line_re.match(line)
            if m:
                mouse.move(int(m.group("x")), int(m.group("y")))
finally:
    process.kill()
