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

import java.io.IOException;
import com.sun.enterprise.config.ConfigContext;
import com.sun.enterprise.server.ApplicationServer;
import com.sun.enterprise.util.SystemPropertyConstants;
import com.sun.enterprise.admin.server.core.AdminService;
import com.sun.enterprise.admin.event.AdminEventListenerException;

import com.sun.enterprise.config.serverbeans.*;

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

import com.sun.enterprise.config.ConfigException;
import com.sun.enterprise.ee.synchronization.SynchronizationException;
import com.sun.enterprise.ee.synchronization.impl.SynchronizationClientImpl;

import java.io.File;
import org.jvnet.glassfish.comms.admin.event.extensions.clb.*;
import org.jvnet.glassfish.comms.util.LogUtil;

public class ConvergedLBPolicyEventListenerImpl implements ConvergedLbPolicyEventListener {
     static final String CONFIG = "config";
    /**
     * Creates a new instance of ConvergedLBEventListenerImpl
     */
    public ConvergedLBPolicyEventListenerImpl() {
    }

    public void handleCreate(ConvergedLbPolicyEvent e) throws AdminEventListenerException
    {
        try{
          synchronizeDCRXml(e);
        }catch(SynchronizationException ex)
        {
            _logger.log(Level.SEVERE, "File Synchronization of DCR file with DAS failed " + ex.getMessage());
            throw new AdminEventListenerException(ex.getMessage());
        }
    }

    public void handleDelete(ConvergedLbPolicyEvent e) throws AdminEventListenerException
    {
         try{
          synchronizeDCRXml(e);
        }catch(SynchronizationException ex)
        {
            _logger.log(Level.SEVERE, "File Synchronization of DCR file with DAS failed " + ex.getMessage());
            throw new AdminEventListenerException(ex.getMessage());
        }
    }
    public void handleUpdate(ConvergedLbPolicyEvent e) throws AdminEventListenerException
    {
       try{
          synchronizeDCRXml(e);
        }catch(SynchronizationException ex)
        {
            _logger.log(Level.SEVERE, "File Synchronization of DCR file with DAS failed " + ex.getMessage());
             throw new AdminEventListenerException(ex.getMessage());
        }
    }
    protected void synchronizeDCRXml(ConvergedLbPolicyEvent e) throws SynchronizationException {

        // connects to DAS
        String dasName = SystemPropertyConstants.DEFAULT_SERVER_INSTANCE_NAME;

        SynchronizationClientImpl sc = new SynchronizationClientImpl(dasName);

        _logger.log(Level.FINE,
                    "Start: Synchronizing DCR XML file from DAS. DAS NAME: " + dasName );
        try {
            sc.connect();
            _logger.log(Level.FINEST,
                    "Dynamic Reconfig: Successfully connected to DAS" );
        } catch (IOException ie) {
           throw new SynchronizationException("Connection to SynchronizationClientImpl failed. IOException occured while trying to connect " + ie.getMessage());
        }
        String instanceRoot = System.getProperty(SystemPropertyConstants.INSTANCE_ROOT_PROPERTY);

        String clbTargetLocation = instanceRoot + File.separator + CONFIG;

        // current server name
        String serverName=ApplicationServer.getServerContext().
                            getInstanceName();
        String dcrXMLFile = getDCRFileName(e, serverName);

        String clbXMLFileName = getCLBConfigName(serverName, e);

        String clbXMLFile =  clbXMLFileName + "." + configName;


        _logger.log(Level.FINEST,
                    "Dynamic Reconfig: Fetching file from DAS. Source File - " + dcrXMLFile + " Target Location - " + clbTargetLocation );

        sc.get(CONFIG + File.separator + dcrXMLFile, clbTargetLocation + File.separator + dcrXMLFile);

        sc.get(CONFIG + File.separator + clbXMLFile, clbTargetLocation + File.separator + clbXMLFile);

        _logger.log(Level.FINE,
                    "Synchronization of DCR file completed sucessfully to " + clbTargetLocation);
        try {
            sc.disconnect();
        } catch (IOException ie) {
           throw new SynchronizationException("Unable to close connection to DAS");
        }
       _logger.log(Level.FINE,
                    "Reloading the configuration...");
        CLBConfigurator.getInstance().reload();
    }

    private String getDCRFileName(ConvergedLbPolicyEvent e, String serverName )
                throws SynchronizationException {
        ConfigContext _ctx = e.getConfigContext();
        try {
            if (_ctx == null ) {
                throw new RuntimeException("ConfigContext is null");
            }
            Config config = ServerHelper.getConfigForServer(_ctx,serverName);

            if (config == null ) {
                throw new RuntimeException("ServerHelper.getConfigForServer is null");
            }

            Domain domain = ServerBeansFactory.getDomainBean(_ctx);

            String configName = config.getAvailabilityService().getConvergedLoadBalancer().getConvergedLbConfigName();

            assert domain != null;

            ConvergedLbConfig clbconfig = domain.getConvergedLbConfigs().getConvergedLbConfigByName(configName);
            if (clbconfig != null && clbconfig.getConvergedLbPolicy() != null)
                return clbconfig.getConvergedLbPolicy().getDcrFile();
            else throw new RuntimeException ("Converged LB Policy is not set for this configuration");


        } catch (ConfigException ce) {
            throw new SynchronizationException("Unable to resolve CLB configuration file name");
        }

    }

   private String configName = null;

    private String getCLBConfigName(String serverName, ConvergedLbPolicyEvent e)
                throws SynchronizationException {
        ConfigContext _ctx = e.getConfigContext();
        try {
            if (_ctx == null ) {
                throw new RuntimeException("ConfigContext is null");
            }
            Config config = ServerHelper.getConfigForServer(_ctx,serverName);
            if (config == null ) {
                throw new RuntimeException("ServerHelper.getConfigForServer is null");
            }

            configName = config.getAvailabilityService().getConvergedLoadBalancer().getName();
            return  config.getAvailabilityService().
                           getConvergedLoadBalancer().getConfigFile();

        } catch (ConfigException ce) {
            throw new SynchronizationException("Unable to resolve CLB configuration file name");
        }

    }


    private static final Logger _logger = LogUtil.CLB_LOGGER.getLogger();



}

