import optparse
import json
from restkit import Resource, BasicAuth, request
import ast

"""This scripts logins to the specified Jira, retrieves any issue
    with more than 4 linked cases, selects the first of those issues and
    prints the linked cases' ids."""

def getLinkedCaseNumbers(issuekey, auth):
    """Returns the case numbers linked to the issuekey."""
    resource = Resource(options.jira_url+('/rest/api/2/issue/%s/properties' % issuekey), filters=[auth])
    response = resource.get(headers={'Content-Type': 'application/json'}) # Retrieves the issue's properties.
    if response.status_int == 200:  # Verifies the response has content in it.
        entity_properties = json.loads(response.body_string())  # Turns the json response into a python dict.

    casenumbers_list = []
    for entity in entity_properties['keys']:
    	if entity['key'].startswith('SF_ENTITY_') :
    		resource = Resource(entity['self'], filters=[auth])
    		response = resource.get(headers={'Content-Type': 'application/json'})  # Retrieves the linked cases.
    		if response.status_int == 200:# Verifies the response has content in it.
        		caseInfo = ast.literal_eval(response.body_string())  # Turns the obtained string into a python dict.
        		casenumbers_list.append(caseInfo['value']['CaseNumber'])
    
    return casenumbers_list  # Returns the case numbers.


def getResolvedIssueKeysWithRelatedCases(auth):
    """Returns the issue keys for resolved issues that have at least 1 linked case."""
    resource = Resource(options.jira_url+'/rest/api/2/search?fields=Key&jql=issue.property[relatedSalesforceEntities].total>0+AND+resolved!=null', filters=[auth])
    response = resource.get(headers={'Content-Type': 'application/json'})
    #TODO: JIRA search REST API returns a max of 50 issues in the response, so we will need iterate over all the paginated results
    if response.status_int == 200:  # Verifying the response has content in it.
        issues = json.loads(response.body_string())  # Turn the json response into a python dict.
        issue_list = [issue['key'] for issue in issues['issues']]  # Cleans any issue info that's not its key.
        return issue_list


def parse_args():
    """Generates command line arguments for the script."""
    parser = optparse.OptionParser()
    parser.add_option('-u', '--user', dest='user',
                      help='Username to access Jira')
    parser.add_option('-p', '--password', dest='password',
                      help='Password to access  Jira')
    parser.add_option('-j', '--jira', dest='jira_url',
                      help='Jira URL')
    return parser.parse_args()  # Returns the user defined command line arguments.


if __name__ == '__main__':

    (options, args) = parse_args()

    auth = BasicAuth(options.user, options.password)  # Script uses basic auth to login to Jira.

    issue_list = getResolvedIssueKeysWithRelatedCases(auth)
    print ('Unresolved Issues with at least 1 related case:')
    print ', '.join(issue_list)
    cases = getLinkedCaseNumbers(issue_list[0], auth)
    print ('The issue %s has the following associated cases:' % issue_list[0])
    print cases
