001/*
002 *  Copyright 2017 Anyware Services
003 *
004 *  Licensed under the Apache License, Version 2.0 (the "License");
005 *  you may not use this file except in compliance with the License.
006 *  You may obtain a copy of the License at
007 *
008 *      http://www.apache.org/licenses/LICENSE-2.0
009 *
010 *  Unless required by applicable law or agreed to in writing, software
011 *  distributed under the License is distributed on an "AS IS" BASIS,
012 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 *  See the License for the specific language governing permissions and
014 *  limitations under the License.
015 */
016package org.ametys.odf.catalog;
017
018import java.util.HashMap;
019import java.util.Map;
020
021import org.ametys.cms.repository.Content;
022import org.ametys.cms.repository.ModifiableContent;
023import org.ametys.odf.translation.TranslationHelper;
024
025/**
026 * This updater updates the translations of created contents after the full catalog copy
027 *
028 */
029public class TranslationUpdater implements CopyCatalogUpdater
030{
031    @Override
032    public void updateContents(String initialCatalogName, String newCatalogName, Map<Content, Content> copiedContents, Content targetParentContent)
033    {
034        for (Content initialContent : copiedContents.keySet())
035        {
036            // Get the translations of initial content
037            Map<String, String> translations = TranslationHelper.getTranslations(initialContent);
038            
039            if (!translations.isEmpty())
040            {
041                Map<String, String> updatedTranslations = new HashMap<>();
042                
043                for (String lang : translations.keySet())
044                {
045                    // For each translation, get its copy in the new catalog
046                    String translatedContentId = translations.get(lang);
047                    
048                    copiedContents.entrySet()
049                                  .stream()
050                                  .filter(entry -> translatedContentId.equals(entry.getKey().getId()))
051                                  .findFirst()
052                                  .map(Map.Entry::getValue)
053                                  .map(Content::getId)
054                                  .ifPresent(copyId -> updatedTranslations.put(lang, copyId));
055                }
056                
057                // Update the translations for created content
058                Content createdContent = copiedContents.get(initialContent);
059                if (createdContent instanceof ModifiableContent modifiableCreatedContent)
060                {
061                    TranslationHelper.setTranslations(modifiableCreatedContent, updatedTranslations);
062                }
063            }
064        }
065    }
066}