/** BEGIN COPYRIGHT BLOCK
 * Copyright (C) 2001 Sun Microsystems, Inc.  Used by permission.
 * Copyright (C) 2005 Red Hat, Inc.
 * All rights reserved.
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; version 2
 * of the License.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 * 
 * END COPYRIGHT BLOCK **/
package com.netscape.management.admserv.panel;

import java.util.*;
import java.net.*;
import com.netscape.management.client.util.*;
import com.netscape.management.client.console.ConsoleInfo;
import com.netscape.management.admserv.config.*;

/**
  *
  * @version 0.1 11/28/97
  * @author miodrag@netscape.com
  */
public class CGIServerSetup extends CGIDataModel {
    private static String _taskURL = "admin-serv/tasks/Configuration/ServerSetup";

    private String _portValue = null;
    private String _addrValue = null;

    public CGIServerSetup(ConsoleInfo consoleInfo) {
        super(consoleInfo, _taskURL);
    }

    public void setAttribute(String attr,
            String val) throws ValidationException {
        super.setAttribute(attr, val);
    }


    /**
      * Encode a list of IP addr or host names to allow in the form of regular expression
      */
    public static String encodeFilterList(Vector members) {
        String regex;
        int size = members.size();
        if (size == 0) {
            regex = "";
        } else if (size == 1) {
            regex = (String) members.elementAt(0);
        } else {
            regex = "(";
            for (int i = 0; i < size; i++) {
                if (i == 0) {
                    regex += (String) members.elementAt(i);
                } else {
                    regex += "|" + (String) members.elementAt(i);
                }
            }
            regex += ")";
        }
        Debug.println("encodeFilterList=" + regex);
        return regex;
    }

    /**
      * Decode a regular expression into the list; Expected format is "(exter1|entry2|entry3)" or
      * just "entry"
      *
      */
    public static Vector parseFilterList(String regex) {
        Vector list = new Vector();
        if (regex == null || regex.length() == 0) {
            ; // nothing to do
        } else if (regex.startsWith("(") && regex.endsWith(")")) {
            String members = regex.substring(1, regex.length() - 1);
            Debug.println("members=" + members);
            StringTokenizer strtok = new StringTokenizer(members, "|");
            while (strtok.hasMoreTokens()) {
                list.addElement(strtok.nextToken());
            }
        } else {
            list.addElement(regex);
        }
        return list;
    }

    /**
      * CGI arguments used in getConfiguration()
     */
    public String getCGIParamsForGetOp() {
        //return "op=get&configuration=";
        return "op=get&" + AttrNames.CONFIG_SERVERPORT + "=&" +
                AttrNames.CONFIG_SERVERADDRESS + "=&" +
                AttrNames.CONFIG_HOSTS + "=&" +
                AttrNames.CONFIG_ADDRESSES + "=&" +
                AttrNames.CONFIG_DSGW + "=&" +
                AttrNames.CONFIG_USER + "=";

    }

    /**
      * CGI arguments used in setConfiguration()
     */
    public String getCGIParamsForSetOp() {
        String op = "op=force_set&";
        Enumeration e = _data.keys();
        while (e.hasMoreElements()) {
            String name = (String) e.nextElement();
            String value = (String)_data.get(name);

            if (name.equals(AttrNames.CONFIG_SERVERPORT) &&
                    value.equals(_portValue)) {
                continue;
            }

            if (name.equals(AttrNames.CONFIG_SERVERADDRESS) &&
                    (_addrValue==null) && (value.length()==0)) {
                continue;
            }

            op += name + "=" + URLByteEncoder.encodeUTF8(value) +
                    (e.hasMoreElements() ? "&":"");
        }

        return op;
    }

    public void load() throws RemoteRequestException {
        super.load();
        if (getAttribute(AttrNames.CONFIG_DSGW) == null) {
            _data.put(AttrNames.CONFIG_DSGW, "on");
            _origData.put(AttrNames.CONFIG_DSGW, "on");
        }

        _portValue = getAttribute(AttrNames.CONFIG_SERVERPORT);
        _addrValue = getAttribute(AttrNames.CONFIG_SERVERADDRESS);

    }

    public void save() throws RemoteRequestException {
        super.save();

        String newPort = getAttribute(AttrNames.CONFIG_SERVERPORT);
        String newAddr = getAttribute(AttrNames.CONFIG_SERVERADDRESS);
        boolean portChanged = false, addrChanged=false;
        Debug.println("newAddr=<"+newAddr + "> prevAddr=<"+_addrValue + ">");

        if (_portValue != null && !_portValue.equals(newPort)) {
            portChanged = true;
            _portValue = newPort;
        }

        if ((_addrValue == null || _addrValue.length() == 0)) {
            // no listen address was previously configured
            addrChanged = (newAddr.length() != 0);
            _addrValue = newAddr;
        }
        else {
            // listen address was previously configured
            addrChanged = !_addrValue.equals(newAddr);
            _addrValue = newAddr;
        }

        if (portChanged || addrChanged) {
            ResourceSet resource = new ResourceSet("com.netscape.management.admserv.panel.panel");
            String msg = resource.getString("adminop", "NeedRestartReconnect");
            ConfigInfoDialog.showDialog(getDialogParent(), msg, "");

            //Create post restart adminURL which is needed for RestartOperation.
            try {
                URL url = new URL(_consoleInfo.getAdminURL());
                String host = (addrChanged && newAddr.length() != 0) ? 
                               newAddr : url.getHost();
                String port = portChanged ?
                               newPort : String.valueOf(url.getPort());
                String postRestartURL =
                        url.getProtocol() + "://" + host + ":" + port + "/";

                Debug.println("oldURL = " +
                        _consoleInfo.getAdminURL() + " postRestartURL = " +
                        postRestartURL);

                IRestartControl restartControl =
                        (IRestartControl)_consoleInfo.get(
                        IRestartControl.ID);
                if (restartControl != null) {
                    restartControl.setPostRestartURL(postRestartURL);
                }
            } catch (Exception e) {
                Debug.println("postRestartURL " + e);
            }
        }
        else {
            ResourceSet resource = new ResourceSet("com.netscape.management.admserv.panel.panel");
            String msg = resource.getString("adminop", "NeedRestart");
            ConfigInfoDialog.showDialog(getDialogParent(), msg, "");
        }

    }
}
