#!/usr/bin/env python
import os
import sys
import argparse
import logging
import pyinotify
import subprocess

__author__ = 'Flavio Martins <flaviomartins@acm.org>'

TODO_SUFFIXES = {'.pdf'}
DONE_SUFFIXES = {'-crop.pdf'}
HOME = os.path.expanduser('~')
DEFAULT_WATCH_DIR = os.path.join(HOME, 'Downloads')
DEFAULT_LOG_FILE = os.path.join(HOME, '.pdfcropd.log')

logger = logging.getLogger(__name__)
logger.addHandler(logging.FileHandler(DEFAULT_LOG_FILE))
logger.setLevel(logging.INFO)


class EventHandler(pyinotify.ProcessEvent):
    def __init__(self, margins):
        self.margins = margins

    def process_IN_MOVED_TO(self, event):
        for suffix in DONE_SUFFIXES:
            if event.pathname.lower().endswith(suffix):
                logger.info('Opening ' + event.pathname)
                with open(os.devnull, 'w') as fp:
                    subprocess.Popen(['xdg-open', event.pathname], stdout=fp, stderr=fp)
                break
        else:
            # suffix not known -> probably not cropped
            process_crop(event.pathname, self.margins)

    def process_IN_CLOSE_WRITE(self, event):
        process_crop(event.pathname, self.margins)

    def process_default(self, event):
        pass


# Customize the PDF crop here
def process_crop(pathname, margins):
    ext = os.path.splitext(pathname)[1].lower()
    if ext in TODO_SUFFIXES:
        logger.info('Processing ' + pathname)
        try:
            logger.info(
                subprocess.check_output(['pdfcrop', '--margins', str(margins), pathname]).decode(sys.stdout.encoding))
        except subprocess.CalledProcessError as e:
            logger.error(e.output)


if __name__ == '__main__':
    logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
    parser = argparse.ArgumentParser()
    parser.add_argument("-d", nargs='+', default=[DEFAULT_WATCH_DIR], required=False, help="watch directories")
    parser.add_argument("--margins", type=int, default=10)
    args = parser.parse_args()

    wm = pyinotify.WatchManager()
    mask = pyinotify.IN_CLOSE_WRITE | pyinotify.IN_MOVED_TO

    notifier = pyinotify.Notifier(wm, EventHandler(args.margins))

    # Add watches
    wdd = wm.add_watch(args.d, mask, rec=True)

    logger.info('pdfcropd started: ' + ' '.join(args.d))
    notifier.loop()
