import pathlib
import hashlib


def check_duplicate_pinnames_files(test_mode=False):
    """Check for duplicate PinNames.h files"""
    mbed_os_root = pathlib.Path(__file__).absolute().parents[3]

    errors = []

    file_hash_dict = dict()

    if test_mode:
        search_dir = pathlib.Path(__file__).parent.joinpath('test_files').absolute()
    else:
        search_dir = mbed_os_root.joinpath('targets')

    for f in search_dir.rglob("PinNames.h"):
        with open(f) as pin_names_file:
            pin_names_file_content = pin_names_file.read()
        file_hash_dict[str(f)] = hashlib.md5(pin_names_file_content.encode('utf-8')).hexdigest()

    rev_dict = {}
    for key, value in file_hash_dict.items():
        rev_dict.setdefault(value, set()).add(key)
    duplicates = [key for key, values in rev_dict.items()
                                if len(values) > 1]

    for duplicate in duplicates:
        print("WARNING: Duplicate files")
        for file_path, file_hash in file_hash_dict.items():
            if file_hash == duplicate:
                errors.append({ "file": file_path, "error": "duplicate file"})
                print("\t" + file_path)

    return errors