import logging
import shutil


def epcr_primers(primerfile, forward_dict, reverse_dict, formattedprimers, copyfile=True):
    """
    Read in the ePCR-formatted primer file, and populate forward and reverse primer dictionaries
    :param primerfile: Name and absolute path to the primer file to parse
    :param forward_dict: Dictionary of all forward primer sequences
    :param reverse_dict: Dictionary of all reverse primer sequences
    :param formattedprimers: Name and absolute path of ePCR-formatted primer file
    :param copyfile: Boolean of whether the primer file should be copied to the formatted primer file path
    :return: Updated forward_dict and reverse_dict
    """
    logging.info('Populating primer dictionaries')
    with open(primerfile, 'r') as primer_file:
        for line in primer_file:
            if len(line.split()) == 5:
                basename, forward_seq, reverse_seq, min_amplicon, max_amplicon = line.rstrip().split()
            elif len(line.split()) == 4:
                basename, forward_seq, reverse_seq, max_amplicon = line.rstrip().split()
            else:
                basename, forward_seq, reverse_seq = line.rstrip().split()
            # Add the current primer sequence to the dictionary
            forward_dict[basename] = forward_seq
            reverse_dict[basename] = reverse_seq
    # Copy the primer file to the location store in self.formattedprimers - makes code reuse easier
    if copyfile:
        try:
            shutil.copyfile(src=primerfile,
                            dst=formattedprimers)
        except shutil.SameFileError:
            pass
    # Return the updated dictionaries
    return forward_dict, reverse_dict