/*
 * ICESOFT COMMERCIAL SOURCE CODE LICENSE V 1.1
 *
 * The contents of this file are subject to the ICEsoft Commercial Source
 * Code License Agreement V1.1 (the "License"); you may not use this file
 * except in compliance with the License. You may obtain a copy of the
 * License at
 * http://www.icesoft.com/license/commercial-source-v1.1.html
 *
 * Software distributed under the License is distributed on an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
 * License for the specific language governing rights and limitations under
 * the License.
 *
 * Copyright 2009-2015 ICEsoft Technologies Canada, Corp. All Rights Reserved.
 */

package com.icesoft.push;

import com.icesoft.push.messaging.MessagePayload;
import com.icesoft.push.messaging.PushMessageService;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletContext;

import org.icepush.NotifyBackURI;
import org.icepush.PushGroupManager;
import org.icepush.servlet.ServletContextConfiguration;

public class LocalPushGroupManager
extends org.icepush.LocalPushGroupManager
implements PushGroupManager {
    private static final Logger LOGGER = Logger.getLogger(LocalPushGroupManager.class.getName());

    private final StatusManager statusManager;

    private PushMessageService pushMessageService;

    public LocalPushGroupManager(final ServletContext servletContext, final ScheduledThreadPoolExecutor executor) {
        super(servletContext);
        statusManager =
            new StatusManager(executor, this, new ServletContextConfiguration("com.icesoft.push", servletContext));
    }

    public void addMember(final String groupName, final PushID pushID) {
        String _id = pushID.getID();
        pushIDMap.putIfAbsent(_id, newPushID(pushID, groupName));
        addMember(groupName, _id);
    }

    public void handleShutdown(final UUID uuid) {
        // Handle graceful or non-graceful shutdown
        statusManager.handleShutdown(uuid);
    }

    public void handleStatus(
        final String sourceNodeAddress, final UUID uuid, final long timestamp,
        final Map<String, PushID.Status> pushIDStatusMap) {

        statusManager.handleStatus(sourceNodeAddress, uuid, timestamp, pushIDStatusMap);
    }

    @Override
    public boolean setNotifyBackURI(Set<String> pushIDSet, NotifyBackURI notifyBackURI, boolean broadcast) {
        if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.log(Level.FINE, "Set NotifyBackURI '" + notifyBackURI + "' for PushIDs '" + pushIDSet + "'.");
        }
        boolean _modified = super.setNotifyBackURI(pushIDSet, notifyBackURI, broadcast);
        if (broadcast && _modified) {
            if (pushMessageService != null) {
                MessagePayload messagePayload = new MessagePayload();
                messagePayload.setPushIDSet(pushIDSet);
                messagePayload.setNotifyBackURI(notifyBackURI.getURI());
                pushMessageService.publish(messagePayload, PushMessageService.SET_NOTIFY_BACK_URI_MESSAGE_TYPE);
            }
        }
        return _modified;
    }

    public void setPushMessageService(final PushMessageService pushMessageService) {
        this.pushMessageService = pushMessageService;
        this.statusManager.setPushMessageService(pushMessageService);
    }

    @Override
    public void shutdown() {
        super.shutdown();
        statusManager.shutdown();
    }

    @Override
    protected org.icepush.PushID newPushID(final String id, final String groupName) {
        PushID _pushID =
            new PushID(
                id, groupName, getPushIDTimeout(), getCloudPushIDTimeout(), getTimeoutTimer(),
                getMinCloudPushInterval(), this, statusManager.getUUID());
        _pushID.startExpiryTimeout();
        return _pushID;
    }

    Map<String, PushID.Status> getPushIDStatusMap() {
        Map<String, PushID.Status> _pushIDStatusMap = new HashMap<String, PushID.Status>();
        for (final org.icepush.PushID pushID : pushIDMap.values()) {
            PushID.Status _status = (PushID.Status)pushID.getStatus();
            _pushIDStatusMap.put(pushID.getID(), new PushID.Status(_status));
            _status.setCloudPushSequenceNumber(-1);
        }
        return _pushIDStatusMap;
    }

    private PushID newPushID(final PushID pushID, final String groupName) {
        PushID _pushID =
            new PushID(
                pushID, groupName, getPushIDTimeout(), getCloudPushIDTimeout(), getTimeoutTimer(),
                getMinCloudPushInterval(), this, statusManager.getUUID());
        _pushID.startExpiryTimeout();
        return _pushID;
    }
}
