import os
import tarfile
import time

def verify_the_existence_of_folder(target_data_dir):
    """Create the target directory if it does not already exist."""

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

def with_progress_bar(func):
    def wrapper(*args, **kwargs):
        items = func(*args, **kwargs)
        func_name = func.__name__
        for i, item in enumerate(items):
            print(f"{func_name}: {i + 1}/{len(items)}")
            yield item

    return wrapper

def extract_tar_file(path, file_name, extract_path):
    """Extract a tar archive to the target directory."""
    file_full_path = os.path.join(path, file_name)
    tar_file = tarfile.open(file_full_path)
    tar_file.extractall(extract_path)
    tar_file.close()

@with_progress_bar
def find_tar_files(path, target):
    """List tar files whose names contain a keyword."""
    tar_files = []
    for file in os.listdir(path):
        if file.endswith('.tar') and target in file:
            tar_files.append(file)
    return tar_files

def handle_nasa_source_data(input_path, output_path, keywords):
    """Extract NASA OceanColor tar archives matching a keyword."""

    verify_the_existence_of_folder(output_path)

    target_files = find_tar_files(input_path, keywords)

    for file in target_files:
        extract_tar_file(input_path, file, output_path)

if __name__ == '__main__':

    handle_nasa_source_data('./01_download_nasa_data', './02_chl_nc_data', 'chl')
    # handle_nasa_source_data('./01_download_nasa_data', './02_par_nc_data', 'par')
