/*
 * 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.icepush;

import org.icepush.Configuration;
import org.icepush.http.Request;
import org.icepush.http.Response;
import org.icepush.http.ResponseHandler;
import org.icepush.http.Server;
import org.icepush.http.standard.RequestProxy;
import org.icepush.util.Slot;

import java.util.logging.Level;
import java.util.logging.Logger;

public class AdjustHeartbeatServer implements Server {
    private static final Logger LOGGER = Logger.getLogger(AdjustHeartbeatServer.class.getName());

    private static final double IntervalExpansionFactor = 1.1;
    private static final double IntervalReductionFactor = 0.75;
    private Server server;
    private Slot heartbeat;
    private long minHeartbeat;
    private long maxHeartbeat;
    private Slot sequenceNo;
    private long heartbeatTimestamp = System.currentTimeMillis();

    public AdjustHeartbeatServer(Slot sequenceNo, Slot heartbeatInterval, final Configuration configuration, Server server) {
        this.sequenceNo = sequenceNo;
        this.server = server;
        this.heartbeat = heartbeatInterval;
        long defaultMinHeartbeatInterval = heartbeat.getLongValue() / 3;
        long defaultMaxHeartbeatInterval = Math.round(3 * heartbeat.getLongValue());
        this.minHeartbeat = configuration.getAttributeAsLong("minHeartbeatInterval", defaultMinHeartbeatInterval);
        this.maxHeartbeat = configuration.getAttributeAsLong("maxHeartbeatInterval", defaultMaxHeartbeatInterval);
    }

    public void service(Request request) throws Exception {
        server.service(new HeartbeatRequest(request));
    }

    public void shutdown() {
        server.shutdown();
    }

    private class HeartbeatRequest extends RequestProxy {
        public HeartbeatRequest(Request request) {
            super(request);
        }

        public void respondWith(final ResponseHandler handler) throws Exception {
            request.respondWith(new UpdateHeartbeatHandler(handler));
        }

        private class UpdateHeartbeatHandler implements ResponseHandler {
            private final ResponseHandler handler;

            public UpdateHeartbeatHandler(ResponseHandler handler) {
                this.handler = handler;
            }

            public void respond(Response response) throws Exception {
                try {
                    long previousSequenceNo;
                    try {
                        previousSequenceNo = request.getHeaderAsLong("ice.push.sequence");
                    } catch (RuntimeException e) {
                        previousSequenceNo = 0;
                    }
                    //if sequence number sent by the client is different than the one
                    //on the server it can be assumed that at least one heartbeat response was lost at some point
                    boolean matchingSequenceNo = previousSequenceNo == sequenceNo.getLongValue();
                    if (matchingSequenceNo) {
                        //increase interval since heartbeat still runs great
                        //increase interval only after the previous interval has elapsed to avoid increasing the value too rapidly
                        if (updateHeartbeat()) {
                            heartbeat.setLongValue(Math.min(maxHeartbeat, Math.round(heartbeat.getLongValue() * IntervalExpansionFactor)));
                        }
                    } else {
                        //decrease interval since heartbeat was lost
                        heartbeat.setLongValue(Math.max(minHeartbeat, Math.round(heartbeat.getLongValue() * IntervalReductionFactor)));
                    }
                    //send heartbeat only when current heartbeat interval has elapsed, this avoids
                    //oscillations or rapid changes in the heartbeat interval
                    if (!matchingSequenceNo || updateHeartbeat()) {
                        response.setHeader("ice.push.heartbeat", heartbeat.getLongValue());
                        heartbeatTimestamp = System.currentTimeMillis();
                    }
                    response.setHeader("ice.push.heartbeatTimestamp", heartbeatTimestamp);
                } finally {
                    handler.respond(response);
                }
            }

            private boolean updateHeartbeat() {
                try {
                    heartbeatTimestamp = Long.parseLong(request.getHeader("ice.push.heartbeatTimestamp"));
                } catch (final NumberFormatException exception) {
                }
                return System.currentTimeMillis() > heartbeat.getLongValue() + heartbeatTimestamp;
            }
        }
    }
}
