import envelopes
import envelopes.connstack
from flask import Flask
import flask
import logging
import os

app = Flask(__name__)
conn = envelopes.SendGridSMTP(
    login=os.environ.get('SENDGRID_USERNAME'),
    password=os.environ.get('SENDGRID_PASSWORD')
)

logging.basicConfig(level=logging.INFO)

@app.before_request
def app_before_request():
    envelopes.connstack.push_connection(conn)


@app.after_request
def app_after_request(response):
    envelopes.connstack.pop_connection()
    return response


@app.route('/')
def index():
    """Redirect to chapel homepage."""
    return flask.redirect('http://chapel-lang.org/', code=301)


@app.route('/commit-email', methods=['POST'])
def commit_email():
    """Receive web hook from github and generate email."""
    json_dict = flask.request.get_json()
    logging.info('json body: {0}'.format(json_dict))

    if json_dict['deleted']:
        logging.info('Branch was deleted, skipping email.')
        return 'nope'

    added = '\n'.join(map(lambda f: 'A {0}'.format(f),
                          json_dict['head_commit']['added']))
    removed = '\n'.join(map(lambda f: 'R {0}'.format(f),
                            json_dict['head_commit']['removed']))
    modified = '\n'.join(map(lambda f: 'M {0}'.format(f),
                             json_dict['head_commit']['modified']))
    changes = '\n'.join([added, removed, modified])

    msg_info = {
        'repo': json_dict['repository']['full_name'],
        'revision': json_dict['head_commit']['url'],
        'message': json_dict['head_commit']['message'],
        'changed_files': changes,
        'pusher': json_dict['pusher']['name'],
        'compare_url': json_dict['compare'],
    }

    sender = os.environ.get('CHAPEL_EMAILER_SENDER')
    recipient = os.environ.get('CHAPEL_EMAILER_RECIPIENT')

    subject = '[{0}] {1}'.format(
        msg_info['repo'],
        msg_info['message'].splitlines()[0])
    body = """Revision: {revision}
Author: {pusher}
Compare: {compare_url}
Log Message:
------------
{message}

Modified Files:
---------------
{changed_files}
""".format(**msg_info)

    msg = envelopes.Envelope(
        to_addr=recipient,
        from_addr=sender,
        subject=subject,
        text_body=body
    )
    smtp = envelopes.connstack.get_current_connection()
    logging.info('Sending email: {0}'.format(msg))
    smtp.send(msg)

    return 'yep'

@@ -756,24 +756,545 @@
 e email.%22%22%22%0A
+%0A    # TODO: look at X-GitHub-Event value (thomasvandoren, 2015-01-19)%0A    # TODO: add secret to webhook and set secret in environment (thomasvandoren, 2015-01-19)%0A    # TODO: then, look at X-GitHub-Signature and verify body. See:%0A    #%0A    #         https://developer.github.com/webhooks/#payloads%0A    #         https://developer.github.com/v3/repos/hooks/#create-a-hook%0A    #         https://github.com/github/github-services/blob/f3bb3dd7/lib/service/http_helper.rb#L77%0A    #%0A    #       (thomasvandoren, 2015-01-19)%0A%0A
     json_dic
@@ -2024,19 +2024,18 @@
 mmit'%5D%5B'
-url
+id
 '%5D,%0A    
@@ -2332,16 +2332,105 @@
 IENT')%0A%0A
+    subject_msg = msg_info%5B'message'%5D.splitlines()%5B0%5D%0A    subject_msg = subject_msg%5B:50%5D%0A
     subj
@@ -2454,25 +2454,16 @@
 .format(
-%0A        
 msg_info
@@ -2475,53 +2475,22 @@
 o'%5D,
-%0A        msg_info%5B'message'%5D.splitlines()%5B0%5D)
+ subject_msg)%0A
 %0A   
@@ -2542,31 +2542,8 @@
 er%7D%0A
-Compare: %7Bcompare_url%7D%0A
 Log 
@@ -2607,16 +2607,16 @@
 -------%0A
-
 %7Bchanged
@@ -2622,16 +2622,40 @@
 d_files%7D
+%0A%0ACompare: %7Bcompare_url%7D
 %0A%22%22%22.for

add todo, update msg format, and ensure short subject