#!/usr/bin/env python
# -*- coding: utf-8 -*-
# PYTHON_ARGCOMPLETE_OK
"""
tc.py <command> [<args>]

Where command is the type of build you with to invoke:
    linux        Neo4j Linux
    power8       Neo4j Power8
    windows      Neo4j Windows
    har          HA Robustness
"""
# StdLib imports first
from __future__ import print_function
from argparse import ArgumentParser
import sys
try:
    import urlparse
except ImportError:
    # Renamed in Python3
    from urllib import parse as urlparse
# Library imports
import requests as r

# Some constants #

# Want to request json from the server
_HEADERS = {'Accept': 'application/json',
            'Content-Type': 'application/xml'}

_REQUESTBASE = """
<build personal="{personal}" branchName="{branch}">
  <buildType id="{buildid}"/>
  <comment><text>Triggered from CLI</text></comment>
  <properties>
    <property name="remote" value="{remote}"/>
    <property name="branch" value="{branch}"/>{props}
  </properties>
</build>
"""

_REQUESTPROPERTYBASE = '\n    <property name="{name}" value="{value}"/>'

_NEO4JLINUX_ID = "JonasHaRequests_Neo4jCustom"
_NEO4JPOWER8_ID = "JonasRequests_Neo4jCustomPower8"
_HAR_ID = "JonasHaRequests_HarBranchArtifacts"
_WIN_ID = "JonasHaRequests_Neo4jCustomWindows"

_LINUX_JDKS = ['openjdk-8', 'openjdk-7',
               'oracle-jdk-8', 'oracle-jdk-7',
               'ibmjdk-8', 'ibmjdk-7']

# End constants #


# Top level parsers

# All builds share teamcity information
_PARSER = ArgumentParser(add_help=False)
_REQUIRED = _PARSER.add_argument_group('mandatory arguments')
_REQUIRED.add_argument('-u', '--user', metavar='USERNAME',
                       help='TeamCity username', required=True)
_REQUIRED.add_argument('-p', '--password',
                       help='TeamCity password', required=True)
_PARSER.add_argument('-r', '--remote', metavar='URL',
                     help='Public remote repo where branch exists',
                     default='origin')
_PARSER.add_argument('--teamcity', metavar='URL',
                     help='Url to TeamCity',
                     default='https://build.neohq.net')
_PERSONAL_PARSER = _PARSER.add_mutually_exclusive_group(required=False)
_PERSONAL_PARSER.add_argument('--personal', dest='personal',
                              action='store_true',
                              help='Start as personal build')
_PERSONAL_PARSER.add_argument('--no-personal', dest='personal',
                              action='store_false',
                              help='Do not start as personal build')
_PARSER.set_defaults(personal=False)

# All Neo4j builds share some obvious arguments
_NEO4JPARSERBASE = ArgumentParser(add_help=False)
_NEO4JPARSERBASE.add_argument('--maven-goals', metavar='GOALS',
                              help='Maven goal(s) to invoke',
                              default='clean verify')
_NEO4JPARSERBASE.add_argument('--maven-args', metavar='ARGS',
                              help='Additional Maven arguments',
                              default='-DrunITs -DskipBrowser')
_NEO4JREQUIRED = _NEO4JPARSERBASE.add_argument_group('mandatory arguments')
_NEO4JREQUIRED.add_argument('-b', '--branch',
                            help=('Branch of Neo4j to checkout.' +
                                  ' For a pr specify "refs/pull/<num>/head"'),
                            required=True)

# End top level parsers

def dict_as_properties(props):
    """
    Format a dictionary as xml property tags:

        <property name=NAME value=VALUE />

    """
    xml = ""
    for k, v in props.items():
        xml += _REQUESTPROPERTYBASE.format(name=k, value=v)
    return xml


def request_xml(buildid, personal, branch, remote, props=None):
    """
    Format an XML build request
    """
    if props is None:
        props = ""

    return _REQUESTBASE.format(buildid=buildid,
                               remote=remote,
                               branch=branch,
                               props=props,
                               personal=str(personal).lower())


def send_request(user, password, url, data):
    """
    Start a build, defined in data
    """
    resp = r.post(urlparse.urljoin(url, "httpAuth/app/rest/buildQueue"),