#!/usr/bin/env python

from optparse import OptionParser, make_option
import sys
import flowdock

option_list = [
    make_option(
        '--api-key',
        action='store',
        dest='api_key',
        type='string',
        help=u'The API key for the FlowDoc API'
    ),
    make_option(
        '--app-name',
        action='store',
        dest='app_name',
        type='string',
        help=u'The application name to post as'
    ),
    make_option(
        '--from-address',
        action='store',
        dest='from_address',
        type='string',
        help=u'An email address to send the post from'
    ),
    make_option(
        '--from-name',
        action='store',
        dest='from_name',
        type='string',
        help=u'The real name associated with the email address'
    ),
    make_option(
        '--subject',
        action='store',
        dest='subject',
        type='string',
        help=u'The subject of the post'
    ),
    make_option(
        '--project',
        action='store',
        dest='project',
        type='string',
        help=u'The human-readable identifier for more detailed categorization'
    ),
    make_option(
        '--tag',
        action='append',
        dest='tags',
        type='string',
        help=u'One argument for each tag to tag this post with'
    ),
    make_option(
        '--link',
        action='store',
        dest='link',
        type='string',
        help=u'A URL to associate with this post'
    ),
    make_option(
        '--show-traceback',
        action='store_true',
        dest='show_traceback',
    )
]

option_defaults = {
    'api_key': flowdock.DEFAULT_API_KEY,
    'app_name': flowdock.DEFAULT_APP_NAME,
    'from_address': None,
    'from_name': None,
    'subject': '',
    'project': None,
    'tags': [],
    'link': None,
    'show_traceback': False,
}

parser = OptionParser(option_list=option_list,
                      version=flowdock.__version__,
                      description='An API Client for FlowDock')
parser.set_defaults(**option_defaults)
options, args = parser.parse_args()
flowdock.DEFAULT_API_KEY = options.api_key
flowdock.DEFAULT_APP_NAME = options.app_name
flowdock.DEFAULT_PROJECT = options.project
try:
    content = sys.stdin.read()
    flowdock.post(options.from_address, options.subject, content,
                  from_name=options.from_name,
                  link=options.link, tags=options.tags)
except Exception, e:
    if options.show_traceback:
        raise
    else:
        sys.stderr.write(u'%s\n' % (e,))
        sys.exit(1)


