/*
 * Copyright 2014-2018 Real Logic Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.aeron.cluster;

import io.aeron.Publication;
import io.aeron.cluster.codecs.*;
import io.aeron.logbuffer.BufferClaim;

class EgressPublisher
{
    private static final int SEND_ATTEMPTS = 3;

    private final BufferClaim bufferClaim = new BufferClaim();
    private final MessageHeaderEncoder messageHeaderEncoder = new MessageHeaderEncoder();
    private final SessionEventEncoder sessionEventEncoder = new SessionEventEncoder();
    private final ChallengeEncoder challengeEncoder = new ChallengeEncoder();
    private final AdminResponseEncoder adminResponseEncoder = new AdminResponseEncoder();

    public boolean sendEvent(final ClusterSession session, final EventCode code, final String detail)
    {
        final Publication publication = session.responsePublication();
        final int length = MessageHeaderEncoder.ENCODED_LENGTH +
            SessionEventEncoder.BLOCK_LENGTH +
            SessionEventEncoder.detailHeaderLength() +
            detail.length();

        int attempts = SEND_ATTEMPTS;
        do
        {
            final long result = publication.tryClaim(length, bufferClaim);
            if (result > 0)
            {
                sessionEventEncoder
                    .wrapAndApplyHeader(bufferClaim.buffer(), bufferClaim.offset(), messageHeaderEncoder)
                    .clusterSessionId(session.id())
                    .correlationId(session.lastCorrelationId())
                    .code(code)
                    .detail(detail);

                bufferClaim.commit();

                return true;
            }
        }
        while (--attempts > 0);

        return false;
    }

    public boolean sendChallenge(final ClusterSession session, final byte[] encodedChallenge)
    {
        final Publication publication = session.responsePublication();
        final int length = MessageHeaderEncoder.ENCODED_LENGTH +
            ChallengeEncoder.BLOCK_LENGTH +
            ChallengeEncoder.encodedChallengeHeaderLength() +
            encodedChallenge.length;

        int attempts = SEND_ATTEMPTS;
        do
        {
            final long result = publication.tryClaim(length, bufferClaim);
            if (result > 0)
            {
                challengeEncoder
                    .wrapAndApplyHeader(bufferClaim.buffer(), bufferClaim.offset(), messageHeaderEncoder)
                    .clusterSessionId(session.id())
                    .correlationId(session.lastCorrelationId())
                    .putEncodedChallenge(encodedChallenge, 0, encodedChallenge.length);

                bufferClaim.commit();

                return true;
            }
        }
        while (--attempts > 0);

        return false;
    }

    public boolean sendAdminResponse(final ClusterSession session, final byte[] encodedResponse)
    {
        final Publication publication = session.responsePublication();
        final int length = MessageHeaderEncoder.ENCODED_LENGTH +
            AdminResponseEncoder.BLOCK_LENGTH +
            AdminResponseEncoder.encodedResponseHeaderLength() +
            encodedResponse.length;

        int attempts = SEND_ATTEMPTS;
        do
        {
            final long result = publication.tryClaim(length, bufferClaim);
            if (result > 0)
            {
                adminResponseEncoder
                    .wrapAndApplyHeader(bufferClaim.buffer(), bufferClaim.offset(), messageHeaderEncoder)
                    .clusterSessionId(session.id())
                    .correlationId(session.lastCorrelationId())
                    .putEncodedResponse(encodedResponse, 0, encodedResponse.length);

                bufferClaim.commit();

                return true;
            }
        }
        while (--attempts > 0);

        return false;
    }
}

@@ -721,16 +721,139 @@
 erClaim;
+%0Aimport org.agrona.ExpandableArrayBuffer;%0A%0Aimport static io.aeron.cluster.ClusterSession.MAX_ENCODED_ADMIN_RESPONSE_LENGTH;
 %0A%0Aclass 
@@ -978,24 +978,135 @@
 ferClaim();%0A
+    private final ExpandableArrayBuffer buffer = new ExpandableArrayBuffer(MAX_ENCODED_ADMIN_RESPONSE_LENGTH);%0A
     private 
@@ -2656,393 +2656,87 @@
     
-final int length = MessageHeaderEncoder.ENCODED_LENGTH +%0A            ChallengeEncoder.BLOCK_LENGTH +%0A            ChallengeEncoder.encodedChallengeHeaderLength() +%0A            encodedChallenge.length;%0A%0A        int attempts = SEND_ATTEMPTS;%0A        do%0A        %7B%0A            final long result = publication.tryClaim(length, bufferClaim);%0A            if (result %3E 0)%0A            %7B%0A        
+if (!publication.isConnected())%0A        %7B%0A            return false;%0A        %7D%0A%0A
     
@@ -2764,32 +2764,24 @@
             
-        
 .wrapAndAppl
@@ -2798,44 +2798,11 @@
 ffer
-Claim.buffer(), bufferClaim.offset()
+, 0
 , me
@@ -2817,32 +2817,24 @@
 derEncoder)%0A
-        
             
@@ -2873,32 +2873,24 @@
             
-        
 .correlation
@@ -2917,32 +2917,24 @@
 lationId())%0A
-        
             
@@ -3014,38 +3014,270 @@
     
-        bufferClaim.commit();%0A
+final int length = MessageHeaderEncoder.ENCODED_LENGTH + challengeEncoder.encodedLength();%0A%0A        int attempts = SEND_ATTEMPTS;%0A        do%0A        %7B%0A            final long result = publication.offer(buffer, 0, length);%0A            if (result %3E 0)%0A            %7B
 %0A   
@@ -3574,399 +3574,87 @@
     
-final int length = MessageHeaderEncoder.ENCODED_LENGTH +%0A            AdminResponseEncoder.BLOCK_LENGTH +%0A            AdminResponseEncoder.encodedResponseHeaderLength() +%0A            encodedResponse.length;%0A%0A        int attempts = SEND_ATTEMPTS;%0A        do%0A        %7B%0A            final long result = publication.tryClaim(length, bufferClaim);%0A            if (result %3E 0)%0A            %7B%0A        
+if (!publication.isConnected())%0A        %7B%0A            return false;%0A        %7D%0A%0A
     
@@ -3686,32 +3686,24 @@
             
-        
 .wrapAndAppl
@@ -3720,44 +3720,11 @@
 ffer
-Claim.buffer(), bufferClaim.offset()
+, 0
 , me
@@ -3739,32 +3739,24 @@
 derEncoder)%0A
-        
             
@@ -3795,32 +3795,24 @@
             
-        
 .correlation
@@ -3839,32 +3839,24 @@
 lationId())%0A
-        
             
@@ -3933,38 +3933,274 @@
     
-        bufferClaim.commit();%0A
+final int length = MessageHeaderEncoder.ENCODED_LENGTH + adminResponseEncoder.encodedLength();%0A%0A        int attempts = SEND_ATTEMPTS;%0A        do%0A        %7B%0A            final long result = publication.offer(buffer, 0, length);%0A            if (result %3E 0)%0A            %7B
 %0A   

Support fragmented responses on cluster egress as this will be required for most cloud environments.