import copy
import itertools


def merge_cropobject_lists(*cropobject_lists):
    """Combines the CropObject lists into one.

    This just means shifting the `objid`s (and thus inlinks
    and outlinks). It is assumed the lists pertain to the same
    image. Uses deepcopy to avoid exposing the original lists
    to modification through the merged list.

    """
    lengths = [len(c) for c in cropobject_lists]
    shift_by = [0] + [sum(lengths[:i]) for i in range(1, len(lengths))]

    new_lists = []
    for clist, s in zip(cropobject_lists, shift_by):
        new_list = []
        for c in clist:
            new_c = copy.deepcopy(c)
            new_c.objid = c.objid + s
            new_c.inlinks = [i + s for i in c.inlinks]
            new_c.outlinks = [o + s for o in c.outlinks]
            new_list.append(new_c)
        new_lists.append(new_list)

    output = list(itertools.chain(*new_lists))

    return output