from datetime import datetime
import logging
from .tool import has_subset_in_string
log = logging.getLogger(__name__)



def locate_files(input_archive_roots, profile, years_list, sitecode, satellites_list,
                      start_yearmonth_analysis ,end_yearmonth_analysis):
    # Search ndvi tif files.
    all_profile_names = []
    all_profile_filepaths = []
    for input_archive_root in input_archive_roots:
        for year_item in years_list:
            profile_dir = input_archive_root.joinpath(str(year_item), sitecode, str(profile).upper())
            log.debug(f"Searching {profile} tif files in directory {profile_dir}.")
            profile_filepaths = list(profile_dir.glob(f"*_{str(profile.lower())}.tif"))
            for profile_filepath in profile_filepaths:

                has_sat_name = has_subset_in_string(profile_filepath.name, satellites_list)

                profile_date_str = profile_filepath.name.split('_')[1]
                profile_date = datetime.strptime(profile_date_str, '%Y-%m-%d')
                profile_in_timeperiod = (profile_date >= start_yearmonth_analysis) and (profile_date <= end_yearmonth_analysis)

                if str(year_item) in profile_filepath.name and has_sat_name and profile_filepath.is_file() and profile_in_timeperiod:
                    if profile_filepath.name not in all_profile_names:
                        all_profile_filepaths.append(profile_filepath)
                        all_profile_names.append(profile_filepath.name)
                        log.info("Found {:s}".format(str(profile_filepath)))
                    else:
                        log.debug("{:s} was already added from {:s}".format(str(profile_filepath.name), str(input_archive_root)))
        if len(all_profile_filepaths) == 0:
            raise Exception("No {:s} .tif files were found in the archives {:s}."
                            .format(profile,",".join([str(fp) for fp in input_archive_roots])))
        log.info(f"List of all input {profile} files:")
        all_profile_filepaths = sorted(sorted(all_profile_filepaths, key=lambda x: x.name))
        for profile_filepath in all_profile_filepaths:
            log.debug(profile_filepath)
    return all_profile_filepaths
