import argparse
import os
import re
import subprocess

def rename_project(hubaddr, project_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)

    project_html_url = '{0}/project/{1}.html'.format(hubaddr,project_id)

    # Download and scrape Project HTML page for old_name_hash
    project_dl=subprocess.Popen(curl_cmd + [project_html_url],
                                stdout=subprocess.PIPE)
    project_page=project_dl.communicate()[0].decode()

    onh_match=re.search(r'<input\s+type="hidden"\s+id="old_name_hash"\s+name="old_name_hash"\s+value="((-?)\d+)">',
                        project_page)

    if onh_match is None:
        print('Could not get project page', project_html_url)
        print('Make sure you have PROJECT_READ permission for this project.')
        exit(1)

    
    # Attempt to rename the project; check the HTTP response code.
    rename_arguments = ['-d', 'old_name_hash={0}'.format(onh_match.group(1)),
                        '-d', 'new_name={0}'.format(newname),
                        project_html_url]
    if not check_page(rename_arguments):
        print('Could not rename project {0}'.format(project_id))
        print('Make sure you have PROJECT_WRITE permission for this project.')
        exit(1)

    # Fetch and output the updated Project 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 + [project_html_url])


# Set up. 
def go():
    parser = argparse.ArgumentParser(
        description=('Rename a project on a CodeSonar hub, '
                     + 'as specified by the command-line arguments.'))
        
    parser.add_argument("hub",
                        help="The hub URL.")
    parser.add_argument("pid",
                        help="The project ID of the project to rename")
    parser.add_argument("newname",
                        help="The new project name; must be URL-encoded.")
    args = parser.parse_args()

    allargs = (args.hub, args.pid, args.newname)
    if not any([a is None for a in allargs]):
        rename_project(*allargs)

go()
