import argparse
import csv
import os
import shutil
import subprocess

# Identify and download the warnings.
def download_warnings(hubaddr, analysis_id, savedir):
    curl_cmd = ['curl']

    def check_page(url):
        http_code = subprocess.check_output(curl_cmd
                                            + ['-w', '%{http_code}',
                                               '-o', os.devnull,
                                               url])
        return (int(http_code.strip())==200)

    analysis_csv_url = f'{hubaddr}/analysis/{analysis_id}.csv'
    out_csv = 'warnings.csv'

    if not check_page(analysis_csv_url):
        print(f'Could not access analysis page for analysis {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)
    
    cmdline = curl_cmd + ['-o', out_csv,
                          analysis_csv_url]
    subprocess.check_call(cmdline)
    search_results=[]
    with open(out_csv, 'r', newline='') as csvfile:
        search_results = csv.DictReader(csvfile)

        firstrow=True
        for row in search_results:
            warning_rel = row['url'].replace('.txt','.html')
            warning_url = f'{hubaddr}{warning_rel}'
            if firstrow:
                if not check_page(warning_url):
                    print(f'Could not access Warning Report {warning_url}.')
                    print(f'Make sure you have ANALYSIS_WARNING_READ permission for analysis {analysis_id}.')
                    exit(1)
                firstrow=False
            dl_cmdline = curl_cmd + ['-o', os.path.basename(warning_rel),
                                     warning_url]
            subprocess.check_call(dl_cmdline)

        if firstrow: 
            # No results: report and exit.
            print('No warnings were found for analysis ID', 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_WARNING_EXISTS permission for the analysis.')
            print('- The analysis has no active warnings.')
            exit(1)


# Set up.
def go():
    parser = argparse.ArgumentParser(
        description=('Download warnings from 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.")
    parser.add_argument("savedir",
                        help="The save directory.")
    args = parser.parse_args()

    allargs = (args.hub, args.aid, args.savedir)
    if not any([a is None for a in allargs]):
        if os.path.isdir(args.savedir):
            print(f'Output directory {args.savedir} exists, deleting and recreating.')
            shutil.rmtree(args.savedir)
        os.mkdir(args.savedir)
        os.chdir(args.savedir)

        download_warnings(*allargs)

go()
