#!/usr/bin/env python

from flask import Flask, request, json
app = Flask(__name__)

from os import environ as env
import urllib, urllib2, base64
import re

# Configure environment via an .env file when running this service

port = int(env['PORT'], 10)
jira_api_url = env['JIRA_API_URL']
jira_web_url = env['JIRA_WEB_URL']
slack_web_url = env['SLACK_WEBHOOK']
jira_id_re = re.compile(r'\[(.+?\-.+?)\]')

def get_jira_id(str):
    match = jira_id_re.search(str)
    if match:
        return match.group(1).upper()
    return None

def json_post(url, data):
    # print 'posting to %s' % url
    encodeddata = json.dumps(data)
    # print 'data: %s' % encodeddata
    response = urllib2.urlopen(url, encodeddata)
    # print 'response: %s\n' % response.getcode()
    return response.read()

def json_get(url, user, password):
    request = urllib2.Request(url)
    base64string = base64.encodestring('%s:%s' % (user, password)).replace('\n', '')
    request.add_header('Authorization', 'Basic %s' % base64string)
    response = urllib2.urlopen(request)
    # print 'response: %s\n' % response.getcode()
    return json.loads(response.read())


def retrieve_jira_info(id):
    user = env['JIRA_USER']
    password = env['JIRA_PASSWORD']
    url = jira_api_url % id # i.e., TGI-11
    # throw away the parts we don't need
    obj = json_get(url, user, password)['fields']
    return {
        'summary': obj['summary'],
        'issuetype': obj['issuetype']['name'],
        'priority': obj['priority']['name'],
        'description': obj['description'],
        'status': obj['status']['name'],
        'project': obj['project']['name'],
        'image': obj['project']['avatarUrls'][ '16x16'],
        'link': jira_web_url % id,
        'id': id
    }
    # add a comment in Jira pointing back to this discussion ?

def post_to_slack(info):
    slack_info = {
        'text': info['message'],
        'icon_emoji': ':jira:',
        'username': 'jira',
        'channel': info['channel_name']
    }
    return json_post(slack_web_url, slack_info)


@app.route('/get_jira_link', methods=["POST"])
def get_jira_link():
    print '\n===============================================\n'
    slack_info = {
        'token': request.form.get('token', 'no token'),
        'team_id': request.form.get('team_id', 'no team id'),
        'channel_id': request.form.get('channel_id', 'no channel id'),
        'channel_name': request.form.get('channel_name', 'no channel name'),
        'user_id': request.form.get('user_id', 'no user id'),
        'user_name': request.form.get('user_name', 'no user name'),
        'command': request.form.get('command', 'no command'),
        'text': request.form.get('text', 'no text'),
        'trigger_word': request.form.get('trigger_word', 'no trigger world')
    }
    print 'slack_info: %s\n' % slack_info
    jira_id = '%s-%s' % (slack_info['command'][1:].upper(), slack_info['text'])
    jira_info = retrieve_jira_info(jira_id)
    print 'jira_info: %s\n' % jira_info
    jira_info['message'] = '%(summary)s <%(link)s|[%(id)s]> (%(issuetype)s, %(priority)s, %(status)s)' % jira_info
    if slack_info['channel_name'] == 'directmessage':
        jira_info['channel_name'] = '@' + slack_info['user_name']
    else:
        jira_info['channel_name'] = '#' + slack_info['channel_name']
    post_to_slack(jira_info)
    return ''

@app.route('/rewrite_jira_link', methods=["POST"])
def rewrite_jira_links():
    # print '\n======================================================\n'
    slack_info = {
        'token': request.form.get('token', 'no token'),
        'team_id': request.form.get('team_id', 'no team id'),
        'channel_id': request.form.get('channel_id', 'no channel id'),
        'channel_name': request.form.get('channel_name', 'no channel name'),
        'user_id': request.form.get('user_id', 'no user id'),
        'user_name': request.form.get('user_name', 'no user name'),
        'text': request.form.get('text', 'no text')
    }
    # print 'slack_info: %s\n' % slack_info
    jira_id = get_jira_id(slack_info['text'])
    if not jira_id:
        return ''
    jira_info = retrieve_jira_info(jira_id)
    # print 'jira_info: %s\n' % jira_info
    jira_info['message'] = '%(summary)s [<%(link)s|%(id)s>] (%(issuetype)s, %(priority)s, %(status)s)' % jira_info
    if slack_info['channel_name'] == 'directmessage':
        jira_info['channel_name'] = '@' + slack_info['user_name']
    else:
        jira_info['channel_name'] = '#' + slack_info['channel_name']
    return json.dumps({'text': jira_info['message'], 'username': 'jira'})



# TEST DATA

test_slack_info = {'channel_id': u'D02R29G43', 'team_id': u'T02R38XRG', 'user_id': u'U02R29G3H', 'token': u'ONcSqUV9PvVtvpPG17VrdiND', 'channel_name': u'@dethe', 'command': u'/tgi', 'text': u'11', 'user_name': u'dethe'}
test_slack_info2 = {'user_id': u'U02R29G3H', 'channel_name': u'support', 'text': u'Testing. Once more, with feeling [tgi-18] is right around here somewhere. Unfortunately, so is [ops-6] which breaks everything.', 'team_id': u'T02R38XRG', 'channel_id': u'C02TDS6AJ', 'token': u'1gwcsmaGDcPJWNxB4yg3J4ZS', 'user_name': u'dethe'}
test_jira_info = {'priority': u'Major', 'status': u'To Do', 'link': u'https://awesense.atlassian.net/browse/TGI-11', 'description': None, 'project': u'Operations', 'issuetype': u'Sub-task', 'image': u'https://awesense.atlassian.net/secure/projectavatar?size=xsmall&pid=10100&avatarId=10011', 'id': u'TGI-11', 'summary': u'Create Place To Document Outages and Maintenance'}
test_jira_info['message'] = '%(summary)s [<%(link)s|%(id)s>] (%(issuetype)s, %(priority)s, %(status)s)' % test_jira_info
test_jira_info['channel_name'] = test_slack_info['channel_name']

if __name__ == '__main__':
    app.run(host="0.0.0.0", port=port)
    # print retrieve_jira_info('TGI-11')
    # print post_to_slack(test_jira_info)
    # print get_jira_id(test_slack_info2['text'])

