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

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

import javax.servlet.ServletContext;

public class ObjectMessage
extends AbstractMessage
implements Message {
    private static final Logger LOGGER = Logger.getLogger(ObjectMessage.class.getName());

    private Serializable object;

    public ObjectMessage(final ServletContext servletContext) {
        super(servletContext);
    }

    public ObjectMessage(final Serializable object, final ServletContext servletContext) {
        super(servletContext);
        setObject(object);
    }

    public void append(final Message message) {
        if (message instanceof ObjectMessage) {
            ObjectMessage _objectMessage = (ObjectMessage)message;
            if (object instanceof Serializable[]) {
                Serializable[] _oldObject = (Serializable[])object;
                Serializable[] _newObject = new Serializable[_oldObject.length + 1];
                for (int i = 0; i < _oldObject.length; i++) {
                    _newObject[i] = _oldObject[i];
                }
                _newObject[_newObject.length - 1] = _objectMessage.getObject();
                object = _newObject;
            } else {
                object = new Serializable[] {object, _objectMessage.getObject()};
            }
        }
    }

    public void clearBody() {
        object = null;
    }

    public int getLength() {
        return -1;
    }

    /**
     * <p>
     *   Gets the Object contained in this ObjectMessage as its body.
     * </p>
     *
     * @return     the Object.
     * @see        #setObject(Serializable)
     */
    public Serializable getObject() {
        return object;
    }

    /**
     * <p>
     *   Sets the specified <code>object</code> as the body of this
     *   ObjectMessage.
     * </p>
     *
     * @param      object
     *                 the Object to be set as the body.
     * @see        #getObject()
     */
    public void setObject(final Serializable object) {
        this.object = object;
    }

    public String toString() {
        return new StringBuffer(super.toString()).append(getObject()).append("\r\n").toString();
    }
}
