#!/usr/bin/env python

#Copyright:: Copyright (c) 2015 PagerDuty, Inc.
#License:: Apache License, Version 2.0
#
#Licensed under the Apache License, Version 2.0 (the "License");
#you may not use this file except in compliance with the License.
#You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
#Unless required by applicable law or agreed to in writing, software
#distributed under the License is distributed on an "AS IS" BASIS,
#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#See the License for the specific language governing permissions and

from ConfigParser import SafeConfigParser
from lib.confluence import Confluence
from jinja2 import Environment, PackageLoader
import argparse
import getpass
import sys
import os
import json


def parse_config(args):
    settings = {}
    parser = SafeConfigParser()
    config_precedence = [
        '/etc/sprintstats.cfg',
        '/usr/local/etc/sprintstats.cfg',
        '~/.sprintstats.cfg',
        'config.cfg'
    ]
    config_file = None
    for f in config_precedence:
        if os.path.exists(f):
            config_file = f

    if args.config:
        if os.path.exists(args.config):
            config_file = args.config
        else:
            sys.stderr.write('WARNING: Specified config file %s not found' % (os.path.abspath(args.config)))
            if config_file and os.path.exists(config_file):
                sys.stderr.write('Using %s instead.' % (os.path.abspath(config_file)))

    if config_file and os.path.exists(config_file):
        parser.read('config.cfg')
        if parser.has_section('default'):
            settings = dict(parser.items('default'))
    if not 'default_points' in settings:
        settings['default_points'] = 0
    return settings


def parse_arguments():
    parser = argparse.ArgumentParser(
        description='Create a new Confluence page with sprint stats')
    parser.add_argument('--user', '-u', metavar='USER',
                        help='The Confluence user name to used for auth. If omitted the current user name will be used.')
    parser.add_argument('--password', '-p', metavar='PASSWORD',
                        help='The Confluence password to be used for auth.')
    parser.add_argument(
        '-P', action='store_true', dest='prompt', help='Prompt for password.')
    parser.add_argument('--server', '-s', metavar='SERVER')
    parser.add_argument(
        '--config', '-c', help='The path to a config file containing Confluence server and/or credentials (See README.md)')
    parser.add_argument(
        '--space', '-e', help='The space that will contain the created/updated page', metavar='SPACE')
    parser.add_argument(
        '--parent', '-r', help='The parent of the created page. (Ignored if the page already exists)', nargs='?', default=None)
    parser.add_argument('--title', '-t', help='The title of the created/updated page')
    args = parser.parse_args()
    return args


def main():
    args = parse_arguments()
    config = parse_config(args)

    user = args.user or (
        'user' in config and config['user']) or getpass.getuser()
    password = args.password or ('password' in config and config['password']) or (
        args.prompt and getpass.getpass())

    if not user or not password:
        sys.stderr.write('Username and password are required')
        return 1

    options = {
        'server': args.server or config['server'] or 'https://confluence.atlassian.com'
    }

    try:
        confluence = Confluence(
            options['server'] + 'wiki/rpc/xmlrpc', user, password)
    except Exception as e:
        sys.stderr.write('ERROR: %s' % (e.message))
        return 1

    if not args.space:
        sys.stderr.write('Wiki space is required')
        return 1
    if not args.title:
        sys.stderr.write('Page title is required')
        return 1

    env = Environment(loader=PackageLoader('templates', ''))
    stats = json.load(sys.stdin)
    page_template = env.get_template('sprint-review.html.j2')
    page_content = page_template.render(**stats)
    page = confluence.get_page(args.space, args.title)
    parent_page_id = None
    if args.parent:
        parent_page = confluence.get_page(args.space, args.parent)
        if parent_page:
            parent_page_id = parent_page['id']
    if page:
        page['content'] = page_content
    else:
        page = {'title': args.title, 'space': args.space, 'content': page_content}
        if parent_page_id:
            page['parentId'] = parent_page_id
    confluence.update_page(page)
    sys.stdout.flush()
    sys.stderr.flush()
    return 0

if __name__ == '__main__':
    sys.exit(main())
