class MongoDbRegionRepository implements RegionRepository {

    @Override
    public Region save(Region item) {
        Page page;
        int index;

        String itemId = item.getId();
        if(itemId == null) {
            page = getPageFromRepository(item);
            page.getRegions().add(item);
            index = page.getRegions().size()-1;
        } else {
            page = getPageByRegionId(itemId);
            index = replaceRegion(page, item);
        }
        // In case we found a subpage
        Page parentPage = page.getParentPage();
        Page saved;
        if (parentPage != null) {
            saved = template.save(parentPage);
            saved = findSubpageByRegionId(itemId, saved);
        } else {
            saved = template.save(page);
        }
        return saved.getRegions().get(index);
    }

}