/*
 * The contents of this file are subject to the terms
 * of the Common Development and Distribution License
 * (the License).  You may not use this file except in
 * compliance with the License.
 *
 * You can obtain a copy of the license at
 * https://glassfish.dev.java.net/public/CDDLv1.0.html or
 * glassfish/bootstrap/legal/CDDLv1.0.txt.
 * See the License for the specific language governing
 * permissions and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL
 * Header Notice in each file and include the License file
 * at glassfish/bootstrap/legal/CDDLv1.0.txt.
 * If applicable, add the following below the CDDL Header,
 * with the fields enclosed by brackets [] replaced by
 * you own identifying information:
 * "Portions Copyrighted [year] [name of copyright owner]"
 *
 * Copyright (c) Ericsson AB, 2004-2007. All rights reserved.
 * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
 */
package org.jvnet.glassfish.comms.replication.dialogmgmt;

import org.jvnet.glassfish.comms.replication.sessmgmt.*;
import com.ericsson.ssa.sip.DialogFragment;
import com.ericsson.ssa.sip.DialogSet;
import com.sun.enterprise.ee.web.sessmgmt.ReplicationState;
import com.sun.enterprise.ee.web.sessmgmt.ReplicationUtil;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Logger;

import org.jvnet.glassfish.comms.util.LogUtil;

/**
 * Based on conversation with Larry and Jan on 11/7, the logic of this class is being considered 
 * to be moved into sipstack. All DialogFragments must be capable of being either inmemory or replicated.
 * All members of DialogFragment must be replicable for dialogfragment to be replicable.  Need to 
 * discuss this on Sailfin replication discussion alias.
 *
 * For now, keep logic here till design agreed upon with Sailfin group.
 *
 * @author jf39279
 */
public class HADialogFragment extends DialogFragment {
    
    private static final Logger _logger = Logger.getLogger(LogUtil.SIP_LOG_DOMAIN);
    
    private static final long serialVersionUID = 1L;
    
    private transient boolean isDirty = false;

    // The version of this DialogFragment
    protected transient AtomicLong version = new AtomicLong(-1);

    protected transient boolean isReplicated = false;

    private transient DialogFragmentExtraParams extraParams;

    private transient String previousOwnerInstanceName;
    private transient String currentOwnerInstanceName;
    private transient long expirationTime;

    /**
     * Constructor.
     * @param ds  dialog set
     */
    public HADialogFragment(DialogSet ds) {
        super(ds);
        extraParams = new DialogFragmentExtraParams(this);
        currentOwnerInstanceName = ReplicationUtil.getInstanceName();      
    }

    /**
     * Gets the name of the instance.that previously owned this DialogFragment.
     *
     * @return The name of the instance that previously owned this DialogFragment
     */
    public String getPreviousOwnerInstanceName() {
        return previousOwnerInstanceName;
    }

    /**
     * Gets the name of the instance.that currently owns this DialogFragment.
     *
     * @return The name of the instance that currently owns this DialogFragment
     */
    public String getCurrentOwnerInstanceName() {
        return currentOwnerInstanceName;
    }
    
    /**
     * Checks whether this is dirty or not.
     *
     * @return true if this has been marked as dirty, false otherwise
     */
    public boolean isDirty() {
        return isDirty;
    }

    /**
     * Marks this session as dirty or non-dirty.
     *
     * @param isDirty The dirty flag
     */
    public void setDirty(boolean isDirty) {
        this.isDirty = isDirty;
    }

    /**
     * Increments the version of this SipApplicationSession.
     */
    public void incrementVersion() {
        version.incrementAndGet();
    }

    /**
     * Gets the version of this SipApplicationSession.
     *
     * @return The version of this SipApplicationSession
     */
    public long getVersion() {
        return version.get();
    }

    /**
     * Sets the version of this SipApplicationSession.
     *
     * @value The new version of this SipApplicationSession
     */
    public void setVersion(long value) {
        version.getAndSet(value);
    }

    /** 
     * is the DialogFragment persistent
     */    
    public boolean isReplicated() {
        return isReplicated;
    }
    
    /** 
     * this sets the persistent flag
     */    
    public void setReplicated(boolean value) {
        isReplicated = value;
    }     
    
   public DialogFragmentExtraParams getExtraParameters() {
        return extraParams;
   }
   
    /**
     * Updates this SipApplicationSession with the given extra 
     * parameters.
     *
     * @param extraParams The serialized SipApplicationSessionExtraParams 
     * used to update this
     * SipApplicationSession
     */
    public void update(byte[] extraParamsState) {        
        
        if(extraParamsState != null) {
            try {
                DialogFragmentExtraParams extraParams 
                    = (DialogFragmentExtraParams)ReplicationState.getObjectValue(extraParamsState);
                setExpirationTime(extraParams.getExpirationTime());
            } catch (Exception ex) {
                _logger.warning("unable to deserialize DialogFragment extraParams for id " + this.getFragmentId() + ":" + ex);
            }
        } 
    }    
   
    /**
     * @serialData Write <code>version</code> as an AtomicLong.
     * @param oos An ObjectOutputStream instance
     * @throws IOException If serialization fails.
     */
    private void writeObject(ObjectOutputStream oos)
            throws IOException {
        oos.writeObject(version);
        oos.writeObject(currentOwnerInstanceName);
        oos.writeLong(expirationTime);
    }

    private void readObject(ObjectInputStream in)
            throws IOException, ClassNotFoundException {
        version = (AtomicLong) in.readObject();
        previousOwnerInstanceName = (String) in.readObject();
        currentOwnerInstanceName = ReplicationUtil.getInstanceName();
        expirationTime = in.readLong();
        extraParams = new DialogFragmentExtraParams(this);
    }

    public String toString() {
        return "id:" + getDialogId() + ":version:" + getVersion(); 
    }
    
    // XXX should I use the PField naming convention here as well?
    // this is only exposed in the HA version at the moment
    public void setExpirationTime(long anExpirationTime) {
        expirationTime = anExpirationTime;
    }
    
    public long getExpirationTime() {
        return expirationTime ;
    }
}
