#!/usr/bin/python
#-*-coding:utf-8-*-
import os
import sys
import requests
import json
import urllib3
import dateutil.parser

class SendData(object):

    def load_file(self, CONFIG, file, type):
        # load spin Jenkins config file
        if not os.path.isfile(CONFIG[file]):
            sys.exit("[ERROR] %s was not found!\n" % CONFIG[file])
        f = open(CONFIG[file], 'r')
        CONFIG[type] = json.loads(f.read())
        f.close()
        print '[CONFIG] %s - load config file.\n'  % type

    def get_data(self, JENKINS, job_name, build_number, type, username, password):
        JENKINS_SESSION = requests.Session()
        JENKINS_SESSION.trust_env = False
        JENKINS['item'] = []
	url = os.getenv(type + '_URL')
        print '[INFO] JENKINS url : ', url, '\n'
        headers = { 'content-type'  : 'application/json', 'Accept-Charset' : 'UTF-8' }
        data_url = url + '/job/' + job_name + '/' + build_number + '/api/json?pretty=true'
        print '[INFO] Prereview test QUERY : ', data_url, '\n'
        JENKINS['raw'] = JENKINS_SESSION.get( data_url, headers=headers, auth=( username, password)).json()

    def get_jira_data(self, JIRA, SEND, type, username, password):
        JIRA_SESSION = requests.Session()
        JIRA_SESSION.trust_env = False

	url = os.getenv(type + '_URL')
        print '[INFO] JIRA QUERY : ', url, '\n'
        headers = { 'content-type'  : 'application/json', 'Accept-Charset' : 'UTF-8' }
        JIRA['raw'] = JIRA_SESSION.get( url, headers=headers, auth=( username, password)).json()
        print '[INFO] get JIRA issues (', len(JIRA['raw']['issues']), ')\n'

        maxlength = 100
        for idx, value in enumerate( JIRA['raw']['issues'] ):

            if idx >= maxlength:
                break

            print 'Start : ' , value['key']

            assign = ' '

            try:
                assign = value['fields']['assignee']['displayName']
            except :
                assign = 'Unassigned'

            if 'NJTS' in value['key']:
                project = 'NJTS'
            elif 'DEVT' in value['key']:
                project = 'DEVT'
            else:
                project = 'NULL'

            if value['fields'].has_key('priority'):
                priority = value['fields']['priority']['name']
            else:
                priority = 'NULL'

            JIRA['item'].append(
            {
                'jira_key' : value['key'],
                'project' : project,
                'title'    : value['fields']['summary'],
                'assignee' : assign,
                'created'  : dateutil.parser.parse( value['fields']['created'] ).strftime('%Y-%m-%d %H:%M:%S'),
                'priority' : priority,
                'status' : value['fields']['status']['name'],
            })

        if len( JIRA['item'] ) > 0:
            SEND['tool_jira_issues'] = JIRA['item']


    def parse_prereviewtest_data(self, JENKINS, SEND):
        for idx, value in enumerate( JENKINS['raw']['actions'][5]['parameters'] ):

            if 'GERRIT_HOST' in value['name']:
                if '10.113.136.109' in value['value']:
                    gerrit = 'SPIN'
                else:
                    gerrit = 'PUBLIC'

            if 'GERRIT_EVENT_TYPE' in value['name']:
                commit_event_type = value['value']

            if 'GERRIT_EVENT_ACCOUNT_NAME' in value['name']:
                committer = value['value']

            if 'GERRIT_PROJECT' in value['name']:
                commit_project = value['value']

            if 'GERRIT_REFNAME' in value['name']:
                commit_branch = value['value']
            elif 'GERRIT_BRANCH' in value['name']:
                commit_branch = value['value']

            if 'GERRIT_NEWREV' in value['name']:
                commit_id = value['value']
            elif 'GERRIT_PATCHSET_REVISION' in value['name']:
                commit_id = value['value']

        JENKINS['item'].append(
        {
            'test_worker_job': JENKINS['raw']['fullDisplayName'],
            'test_type': 'prereview test',
            'test_status': JENKINS['raw']['result'],
            'test_date': JENKINS['raw']['id'],
            #'test_date': dateutil.parser.parse( JENKINS['raw']['id'] ).strftime('%Y-%m-%d %H:%M:%S'),
            'commit_event_type': commit_event_type,
            'commit_branch': commit_branch,
            'commit_project': commit_project,
            'committer': committer,
            'commit_id': commit_id,
            'gerrit': gerrit,
        })

        if len( JENKINS['item'] ) > 0:
            SEND['tool_prereviewtest_status'] = JENKINS['item']
        print ( SEND )

    def parse_functiontest_data(self, JENKINS, SEND):
        commit_event_type = 'NULL'
        commit_branch = 'NULL'
        commit_project = 'NULL'
        committer = 'NULL'
        for idx, value in enumerate( JENKINS['raw']['actions'] ):
            if 'parameters' in value:
                for i, v in enumerate( value['parameters'] ):
                    if 'TRIGGER_INFO' in v['name']:
                        #Daily Build case
                        if v['value'] == 'NULL':
                            commit_id = JENKINS['raw']['id'][0:10]
                        else:
                        # Auto trigger
                            commit_id = v['value']

                    '''if 'TRIGGER_INFO_event_type' in v['name']:
                        commit_event_type = v['value']
                    if 'TRIGGER_INFO_branch' in v['name']:
                        commit_branch = v['value']
                    if 'TRIGGER_INFO_project' in v['name']:
                        commit_project = v['value']
                    if 'TRIGGER_INFO_committer' in v['name']:
                        committer = v['value']'''

        if '10.113.136.111' in JENKINS['raw']['url']:
            gerrit = 'SPIN'
        else:
            gerrit = 'PUBLIC'
        if 'function-test' in JENKINS['raw']['url']:
            test_type = 'function test'
        if 'full-test' in JENKINS['raw']['url']:
            test_type = 'full test'

        index = JENKINS['raw']['fullDisplayName'].index('#')
        print (index)

        JENKINS['item'].append(
        {
            'test_worker_job': JENKINS['raw']['fullDisplayName'],
            'test_type': test_type,
            'test_status': JENKINS['raw']['result'],
            #'test_date': dateutil.parser.parse( JENKINS['raw']['id'] ).strftime('%Y-%m-%d %H:%M:%S'),
            'test_date': JENKINS['raw']['id'],
            'commit_event_type': commit_event_type,
            'commit_branch': commit_branch,
            'commit_project': commit_project,
            'committer': committer,
            'commit_id': commit_id,
            'gerrit': gerrit,
        })
        if len( JENKINS['item'] ) > 0:
            SEND['tool_prereviewtest_status'] = JENKINS['item']
        print ( SEND )



    def send_data(self, CONFIG, SEND):
        with open('jiradata.txt', 'w') as outfile:
            json.dump(SEND, outfile)

        CONFIG['DATA_JENKINS']['params'] = {"parameter" : [ {"name": "jiradata.txt", "file": "file0"},]}

        with open("jiradata.txt", "rb") as f:
            file_data = f.read()

        data, content_type = urllib3.encode_multipart_formdata([
                                                                ("file0", (f.name, file_data)),
                                                                ("json", json.dumps(CONFIG['DATA_JENKINS']['params'])),
                                                                ("Submit", "Build"),
                                                               ])
        if 'token' in CONFIG['DATA_JENKINS'].keys():
            #url = '%s/job/%s/buildWithParameters?token=%s' % (CONFIG['DATA_JENKINS']['url'], CONFIG['DATA_JENKINS']['job'], CONFIG['DATA_JENKINS']['token'])
            url = '%s/job/%s/buildWithParameters?token=%s' % (os.getenv("DATA_JENKINS_URL"), CONFIG['DATA_JENKINS']['job'], CONFIG['DATA_JENKINS']['token'])
            result = requests.post(url, data=data, headers={"content-type": content_type}, verify=False)
        else:
            #url = '%s/job/%s/buildWithParameters' % (CONFIG['DATA_JENKINS']['url'], CONFIG['DATA_JENKINS']['job'])
            url = '%s/job/%s/buildWithParameters' % ( os.getenv("DATA_JENKINS_URL"), CONFIG['DATA_JENKINS']['job'])
            result = requests.post(url, auth=( os.getenv("DATA_JENKINS_USER"), os.getenv("DATA_JENKINS_PW")), data=data, headers={"content-type": content_type}, verify=False)



if __name__ == "__main__":

    CONFIG = {
        'file_jenkins'       : 'config.jenkins',
        'DATA_JENKINS'       : {}
    }

    sender = SendData()

    # load data jenkins config file
    sender.load_file(CONFIG, 'file_jenkins', 'DATA_JENKINS')

    # get job name and build name
    job_name = os.getenv("jobName")
    build_number = os.getenv("buildNumber")
    print "job_name = %s,  buildNumber = %s\n" %(job_name, build_number)

    if job_name is not None and build_number is not None:
        JENKINS = {}
        SEND = {}
        sender.get_data(JENKINS, job_name, build_number, 'SPIN_JENKINS', os.getenv("SPIN_JENKINS_USER"), os.getenv("SPIN_JENKINS_PW"))

        if 'function-test' in job_name or 'full-test' in job_name:
        # function test data in spin jenkins
            sender.parse_functiontest_data(JENKINS, SEND)
        else:
        # prereview test data in spin jenkins
            sender.parse_prereviewtest_data(JENKINS, SEND)

    else:
        JIRA = {}
        JIRA['item'] = []
        SEND = {}

        # get data in spin jira
        sender.get_jira_data(JIRA, SEND, 'SPIN_JIRA', os.getenv("SPIN_JIRA_USER"), os.getenv("SPIN_JIRA_PW"))

        # get data in dev jira
        sender.get_jira_data(JIRA, SEND, 'PUBLIC_JIRA', os.getenv("PUBLIC_JIRA_USER"), os.getenv("PUBLIC_JIRA_PW"))

    sender.send_data(CONFIG, SEND)



