import numpy as np

from .condense import condense
from .delete import delete


def delete_border(im_label):
    """
    Deletes objects touching the border of the image and relabel

    Parameters
    ----------
    im_label : array_like
        A label mask generated by segmentation methods.

    Returns
    -------
    im_label_del : array_like
        A label mask where in all the objects touching the image border have
        been deleted

    See Also
    --------
    histomicstk.segmentation.label.delete

    """
    if not np.any(im_label):
        return im_label

    im_border_mask = np.zeros_like(im_label)
    im_border_mask[:, 0] = 1
    im_border_mask[:, -1] = 1
    im_border_mask[0, :] = 1
    im_border_mask[-1, :] = 1

    border_indices = np.unique(im_label[im_border_mask > 0])
    border_indices = border_indices[border_indices > 0]

    if len(border_indices) == 0:
        return im_label

    # Condense and delete the border regions from the image label
    im_label_del = np.zeros_like(im_label)
    im_label_del = condense(delete(im_label, border_indices))
    return im_label_del
