from copy import deepcopy


def get_nn(seqdict, positions, nn, base):
    """
    Returns nn nearest neigbour bases on either side of the imput positions (i.e. a 2nn+1 mer)

    Parameters
    ----------
    seqdict : dictionary in the format returned by seq_dict()

    positions : list containing positions in the format id_position or chr_position

    nn : int - number of nearest neighbours

    base : either a string (enter single base) or None
            Replaces the middle position of the kmer with the base indicated
            in base and adds it in addition to identical kmer

    Returns
    -------
    nmers : list of nmer strings
    """

    nmers = []
    for pos in positions:
        loc = pos.split("_")

        join = deepcopy(loc)
        del join[-1]
        join = "_".join(join)
        seq = seqdict[join]
        if ((int(loc[-1]) - (nn + 1)) < 0) or ((int(loc[-1]) + nn) > len(seq)):
            print("skipped site {}".format(loc[-1]))  # edge of sequence no neighbours
            continue
        nmer = seq[(int(loc[-1]) - (nn + 1)) : (int(loc[-1]) + nn)]
        nmers.append(nmer)
        if base != None:
            nmer_baseswitch = list(nmer)
            nmer_baseswitch[nn] = str(base)
            nmer_baseswitch = "".join(nmer_baseswitch)
            nmers.append(nmer_baseswitch)

    return nmers