001/*
002 *  Copyright 2023 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.web.synchronization;
017
018import java.util.Map;
019
020import javax.jcr.Node;
021import javax.jcr.RepositoryException;
022import javax.jcr.Session;
023
024import org.ametys.core.observation.Event;
025import org.ametys.web.ObservationConstants;
026import org.ametys.web.repository.page.ZoneItem;
027import org.ametys.web.repository.sitemap.Sitemap;
028
029/**
030 * Synchronize the sitemap zones elements 
031 */
032public class SynchronizeSitemapZonesObserver extends AbstractSynchronizeObserver
033{
034    public boolean supports(Event event)
035    {
036        String id = event.getId();
037        return id.equals(ObservationConstants.EVENT_ZONEITEM_ADDED) || id.equals(ObservationConstants.EVENT_ZONEITEM_MOVED) || id.equals(ObservationConstants.EVENT_ZONEITEM_DELETED) || id.equals(ObservationConstants.EVENT_ZONEITEM_MODIFIED)
038            || id.equals(ObservationConstants.EVENT_VIEW_PARAMETERS_MODIFIED)
039            || id.equals(ObservationConstants.EVENT_SERVICE_MODIFIED); 
040    }
041
042    @Override
043    protected void _internalObserve(Event event, Session liveSession) throws RepositoryException
044    {
045        Sitemap sitemap = null;
046        
047        Map<String, Object> arguments = event.getArguments();
048        if (arguments.get(ObservationConstants.ARGS_SITEMAP_ELEMENT) instanceof Sitemap s2)
049        {
050            sitemap = s2;
051        }
052        else if (arguments.get(ObservationConstants.ARGS_ZONE_ITEM) instanceof ZoneItem zi)
053        {
054            if (zi.getZone().getSitemapElement() instanceof Sitemap s2)
055            {
056                sitemap = s2;
057            }
058        }
059
060        if (sitemap != null)
061        {
062            Node sitemapNode = sitemap.getNode();
063            String sitemapNodePath = sitemapNode.getPath();
064            
065            if (liveSession.itemExists(sitemapNodePath))
066            {
067                Node clonedSitemapNode = (Node) liveSession.getItem(sitemapNodePath);
068                _synchronizeComponent.cloneZones(sitemapNode, sitemap, clonedSitemapNode);
069                
070                liveSession.save();
071            }
072        }
073    }
074}