import json
from setuphelpers import *
from urllib.parse import urlparse

def download_cots(download_directory = r'/root/cots_download'):

    mkdirs(download_directory)

    with open('python_sbom.cdx.json', 'r') as f:
        data = json.load(f)

    for component in data['components']:
        #print(component)
        name = component['name']
        version = component['version']
        orig_url = component['externalReferences'][0]['url']
        sha256 = component['hashes'][0]['content']

        filename = urlparse(orig_url)[2].split('/')[-1]
        # no need of https as we check hash and there is no confidentiality needs here
        binary_cache_url = 'http://srvtemplates.ad.tranquil.it/binary_cache/%s' % filename
        print(name,version,binary_cache_url, sha256)

        wget(binary_cache_url,target=download_directory, connect_timeout=60, resume=True, sha256=sha256)

def get_cots_filename(component_name):

    with open('python_sbom.cdx.json', 'r') as f:
        data = json.load(f)

    for component in data['components']:
        #print(component)
        name = component['name']
        if name == component_name:
            orig_url = component['externalReferences'][0]['url']
            filename = urlparse(orig_url)[2].split('/')[-1]
            return filename
    raise Exception('Wrong component name')

def get_cots_version(component_name):

    with open('python_sbom.cdx.json', 'r') as f:
        data = json.load(f)

    for component in data['components']:
        #print(component)
        name = component['name']
        if name.lower() == component_name.lower():
            return component['version']
    raise Exception('Wrong component name')



