"""This module contains functions for downloading NVD CVE data feeds and for deleting them."""

import datetime
import os
import urllib.request
import zipfile


def download_necessary_files(path):
    """
    Download CVE files.

    :param path: path to directory where the CVE data are stored
    :return None
    """

    if not os.path.exists(path):
        os.makedirs(path)

    i = 2002
    while i <= datetime.datetime.now().year:
        if not os.path.exists(os.path.join(path, 'nvdcve-1.1-{0}.json'.format(i))):
            urllib.request.urlretrieve(
                'https://nvd.nist.gov/feeds/json/cve/1.1/nvdcve-1.1-{0}.json.zip'.format(i),
                os.path.join(path, 'nvdcve-1.1-{0}.zip'.format(i)))
        with zipfile.ZipFile(os.path.join(path, 'nvdcve-1.1-{0}.zip'.format(i)), 'r') as cve_zip:
            cve_zip.extractall(path)
        i += 1


def delete_necessary_files(path):
    """
    Delete downloaded CVE files because they will change and must be downloaded
    again.

    :param path: path to directory where the CVE data are stored
    :return: None
    """
    i = 2002
    while i <= datetime.datetime.now().year:
        os.remove(os.path.join(path, 'nvdcve-1.1-{0}.zip'.format(i)))
        os.remove(os.path.join(path, 'nvdcve-1.1-{0}.json'.format(i)))
        i += 1
    os.rmdir(path)
