import argparse
import subprocess
import os

# Rename the analysis.
def rename_analysis(hubaddr, analysis_id, newname):
    curl_cmd = ['curl']

    def check_page(inarg):
        args = ['-o', os.devnull, '-w', '%{http_code}']
        if isinstance(inarg, str):
            args = args + [inarg]
        else:
            args = args + inarg
        http_code = subprocess.check_output(curl_cmd + args)
        return (int(http_code.strip())==200)

    # Make sure the Analysis page is accessible.
    analysis_html_url = '{0}/analysis/{1}.html'.format(hubaddr,analysis_id)
    if not check_page(analysis_html_url):
        print('Could not access analysis page for analysis {0}'.format(analysis_id))
        print('This may indicate one or more of the following.')
        print('- The analysis ID was not specified correctly.') 
        print('- You do not have ANALYSIS_READ permission for the analysis')
        exit(1)

    # Attempt to rename the analysis; check the HTTP response code.
    rename_arguments = ['-d', 'new_name={0}'.format(newname),
                        analysis_html_url]
    # ; check HTTP response code.
    if not check_page(rename_arguments):
        print('Could not rename analysis {0}'.format(analysis_id))
        print('Make sure you have ANALYSIS_WRITE permission for this analysis.')
        exit(1)
       
    # Fetch and output the updated Analysis page on success.  This is
    # not necessary and can be commented out: it just ensures that
    # the script outputs the updated page as specified in the Task description.
    subprocess.check_call(curl_cmd + [analysis_html_url])


# Set up. 
def go():
    parser = argparse.ArgumentParser(
        description=('Rename an analysis on a CodeSonar hub, '
                     + 'as specified by the command-line arguments.'))
        
    parser.add_argument("hub",
                        help="The hub URL.")
    parser.add_argument("aid",
                        help="The analysis ID of the analysis to rename")
    parser.add_argument("newname",
                        help="The new analysis name; must be URL-encoded.")
    args = parser.parse_args()

    allargs = (args.hub, args.aid, args.newname)
    if not any([a is None for a in allargs]):
        rename_analysis(*allargs)

go()
