/*   **********************************************************************  **
 **   Copyright notice                                                       **
 **                                                                          **
 **   (c) 2003-2006 RSSOwl Development Team                                  **
 **   http://www.rssowl.org/                                                 **
 **                                                                          **
 **   All rights reserved                                                    **
 **                                                                          **
 **   This program and the accompanying materials are made available under   **
 **   the terms of the Eclipse Public License 1.0 which accompanies this     **
 **   distribution, and is available at:                                     **
 **   http://www.rssowl.org/legal/epl-v10.html                               **
 **                                                                          **
 **   A copy is found in the file epl-v10.html and important notices to the  **
 **   license from the team is found in the textfile LICENSE.txt distributed **
 **   in this package.                                                       **
 **                                                                          **
 **   This copyright notice MUST APPEAR in all copies of the file!           **
 **                                                                          **
 **   Contributors:                                                          **
 **     RSSOwl - initial API and implementation (bpasero@rssowl.org)         **
 **                                                                          **
 **  **********************************************************************  */

package net.sourceforge.rssowl.controller.properties;

import net.sourceforge.rssowl.controller.GUI;
import net.sourceforge.rssowl.model.Category;
import net.sourceforge.rssowl.util.GlobalSettings;
import net.sourceforge.rssowl.util.shop.FontShop;
import net.sourceforge.rssowl.util.shop.LayoutDataShop;
import net.sourceforge.rssowl.util.shop.LayoutShop;
import net.sourceforge.rssowl.util.shop.ProxyShop;
import net.sourceforge.rssowl.util.shop.WidgetShop;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Spinner;
import org.eclipse.swt.widgets.Text;

/**
 * Class displays a PropertyPage to set Connection settings for RSSOwl
 * 
 * @author <a href="mailto:bpasero@rssowl.org">Benjamin Pasero </a>
 * @version 1.2.3
 */
public class ConnectionProperties extends PropertyPage {

  /** Max. number of connections at the same time */
  private static final int MAX_CONNECTION_COUNT = 999;

  /** Max. connection timeout in seconds */
  private static final int MAX_CONNECTION_TIMEOUT = 999;

  /** Min. number of connections at the same time */
  private static final int MIN_CONNECTION_COUNT = 1;

  /** Min. connection timeout in seconds */
  private static final int MIN_CONNECTION_TIMEOUT = 1;

  private Spinner conCountSpinner;
  private Spinner conTimeoutSpinner;
  private Text textHost;
  private Text textPort;
  Button checkUpdateAll;
  Button checkUseAuthentification;
  Button checkUseProxy;
  Text textDomain;
  Text textPassword;

  Text textUsername;

  /**
   * Instatiate a new ConnectionProperties PropertyPage
   * 
   * @param parent Composite's parent
   * @param rssOwlGui The MainController
   */
  public ConnectionProperties(Composite parent, GUI rssOwlGui) {
    super(parent, rssOwlGui);
  }

  /**
   * @see net.sourceforge.rssowl.controller.properties.PropertyPage#applyButtonPressed()
   */
  public void applyButtonPressed() {
    GlobalSettings.maxConnectionCount = conCountSpinner.getSelection();
    GlobalSettings.connectionTimeout = conTimeoutSpinner.getSelection();
    updateProxySettings();

    /** Only update tree if flag is TRUE */
    if (checkUpdateAll.getSelection())
      Category.getRootCategory().setUseProxy(ProxyShop.isUseProxy());

    updatePropertiesChangeManager();
  }

  /**
   * @see net.sourceforge.rssowl.controller.properties.PropertyPage#updatePropertiesChangeManager()
   */
  public void updatePropertiesChangeManager() {
    propertyChangeManager.getProxySettingsSave().put("proxySet", String.valueOf(checkUseProxy.getSelection()));
    propertyChangeManager.getProxySettingsSave().put("proxyHost", textHost.getText());
    propertyChangeManager.getProxySettingsSave().put("proxyPort", textPort.getText());
    propertyChangeManager.getProxySettingsSave().put("username", textUsername.getText());
    propertyChangeManager.getProxySettingsSave().put("password", textPassword.getText());
    propertyChangeManager.getProxySettingsSave().put("domain", textDomain.getText());
    propertyChangeManager.setUpdateProxyForAllFavorites(checkUpdateAll.getSelection());
    propertyChangeManager.setUseAuthentification(checkUseAuthentification.getSelection());
    propertyChangeManager.setMaxConnectionCount(conCountSpinner.getSelection());
    propertyChangeManager.setConnectionTimeout(conTimeoutSpinner.getSelection());
  }

  /**
   * Disable components for Proxy Authentification
   */
  private void disableAuthentification() {
    textUsername.setEnabled(false);
    textPassword.setEnabled(false);
    textDomain.setEnabled(false);
    checkUseAuthentification.setSelection(false);
  }

  /** Update Proxy GlobalSettings from the changes the user has made */
  private void updateProxySettings() {
    ProxyShop.setUseProxy(String.valueOf(checkUseProxy.getSelection()));
    ProxyShop.setHost(textHost.getText());
    ProxyShop.setPort(textPort.getText());

    /** Username and Password set */
    if (checkUseAuthentification.getSelection()) {
      ProxyShop.setUsername(textUsername.getText());
      ProxyShop.setPassword(textPassword.getText());
      ProxyShop.setDomain(textDomain.getText());
    }

    /** Username and Password not given */
    else {
      ProxyShop.setUsername("");
      ProxyShop.setPassword("");
      ProxyShop.setDomain("");
    }
  }

  /**
   * @see net.sourceforge.rssowl.controller.properties.PropertyPage#initComponents()
   */
  protected void initComponents() {

    /** Group holding the proxy settings */
    Group proxyGroup = new Group(composite, SWT.NONE);
    proxyGroup.setLayoutData(LayoutDataShop.createGridData(GridData.VERTICAL_ALIGN_BEGINNING | GridData.FILL_HORIZONTAL, 2));
    proxyGroup.setText(GUI.i18n.getTranslation("MENU_PROXY"));
    proxyGroup.setLayout(LayoutShop.createGridLayout(2, 5, 5, 10));
    proxyGroup.setFont(FontShop.dialogFont);

    Composite topHolder = new Composite(proxyGroup, SWT.NONE);
    topHolder.setLayoutData(LayoutDataShop.createGridData(GridData.FILL_HORIZONTAL, 2));
    topHolder.setLayout(new GridLayout(2, false));

    /** Use proxy Button */
    checkUseProxy = new Button(topHolder, SWT.CHECK);
    checkUseProxy.setLayoutData(LayoutDataShop.createGridData(GridData.FILL_HORIZONTAL, 2));
    checkUseProxy.setText(GUI.i18n.getTranslation("LABEL_USE_PROXY"));
    checkUseProxy.setFont(dialogFont);

    /** Host Label */
    Label labelHost = new Label(proxyGroup, SWT.NONE);
    labelHost.setText(GUI.i18n.getTranslation("LABEL_PROXY_HOST") + ": ");
    labelHost.setFont(dialogFont);
    labelHost.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_CENTER | GridData.HORIZONTAL_ALIGN_BEGINNING));

    textHost = new Text(proxyGroup, SWT.BORDER);
    textHost.setFont(dialogFont);
    textHost.setText((String) propertyChangeManager.getProxySettingsSave().get("proxyHost"));
    textHost.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING | GridData.FILL_HORIZONTAL));

    /** Tweak Text Widget */
    WidgetShop.tweakTextWidget(textHost);

    /** Port label */
    Label labelPort = new Label(proxyGroup, SWT.NONE);
    labelPort.setText(GUI.i18n.getTranslation("LABEL_PROXY_PORT") + ": ");
    labelPort.setFont(dialogFont);
    labelPort.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_CENTER | GridData.HORIZONTAL_ALIGN_BEGINNING));

    textPort = new Text(proxyGroup, SWT.BORDER);
    textPort.setFont(dialogFont);
    textPort.setText((String) propertyChangeManager.getProxySettingsSave().get("proxyPort"));
    textPort.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING | GridData.FILL_HORIZONTAL));

    /** Tweak Text Widget */
    WidgetShop.tweakTextWidget(textPort);

    Composite middleHolder = new Composite(proxyGroup, SWT.NONE);
    middleHolder.setLayoutData(LayoutDataShop.createGridData(GridData.FILL_HORIZONTAL, 2));
    middleHolder.setLayout(new GridLayout(2, false));

    /** Use authentification Button */
    checkUseAuthentification = new Button(middleHolder, SWT.CHECK);
    checkUseAuthentification.setLayoutData(LayoutDataShop.createGridData(GridData.FILL_HORIZONTAL, 2));
    checkUseAuthentification.setText(GUI.i18n.getTranslation("LABEL_PROXY_AUTHENTIFICATION"));
    checkUseAuthentification.setFont(dialogFont);

    /** Username label */
    Label labelUsername = new Label(proxyGroup, SWT.NONE);
    labelUsername.setText(GUI.i18n.getTranslation("LABEL_USERNAME") + ": ");
    labelUsername.setFont(dialogFont);
    labelUsername.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_CENTER | GridData.HORIZONTAL_ALIGN_BEGINNING));

    textUsername = new Text(proxyGroup, SWT.BORDER);
    textUsername.setFont(dialogFont);
    textUsername.setText((String) propertyChangeManager.getProxySettingsSave().get("username"));
    textUsername.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING | GridData.FILL_HORIZONTAL));

    /** Tweak Text Widget */
    WidgetShop.tweakTextWidget(textUsername);

    /** Password label */
    Label labelPassword = new Label(proxyGroup, SWT.NONE);
    labelPassword.setText(GUI.i18n.getTranslation("LABEL_PASSWORD") + ": ");
    labelPassword.setFont(dialogFont);
    labelPassword.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_CENTER | GridData.HORIZONTAL_ALIGN_BEGINNING));

    textPassword = new Text(proxyGroup, SWT.BORDER | SWT.PASSWORD);
    textPassword.setFont(dialogFont);
    textPassword.setText((String) propertyChangeManager.getProxySettingsSave().get("password"));
    textPassword.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING | GridData.FILL_HORIZONTAL));

    /** Tweak Text Widget */
    WidgetShop.tweakTextWidget(textPassword);

    /** Domain label */
    Label labelDomain = new Label(proxyGroup, SWT.NONE);
    labelDomain.setText(GUI.i18n.getTranslation("LABEL_DOMAIN") + ": ");
    labelDomain.setFont(dialogFont);
    labelDomain.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_CENTER | GridData.HORIZONTAL_ALIGN_BEGINNING));

    textDomain = new Text(proxyGroup, SWT.BORDER);
    textDomain.setFont(dialogFont);
    textDomain.setText((String) propertyChangeManager.getProxySettingsSave().get("domain"));
    textDomain.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING | GridData.FILL_HORIZONTAL));

    /** Tweak Text Widget */
    WidgetShop.tweakTextWidget(textDomain);

    /** Enable / Disabled Input fields for username / password */
    checkUseAuthentification.addSelectionListener(new SelectionAdapter() {
      public void widgetSelected(SelectionEvent e) {
        textUsername.setEnabled(checkUseAuthentification.getSelection());
        textPassword.setEnabled(checkUseAuthentification.getSelection());
        textDomain.setEnabled(checkUseAuthentification.getSelection());
      }
    });

    /** Enable / Disable input fields for proxy settings */
    checkUseProxy.addSelectionListener(new SelectionAdapter() {
      public void widgetSelected(SelectionEvent e) {
        if (checkUseProxy.getSelection()) {
          setEnabledComponents(true);
        } else {
          setEnabledComponents(false);
        }
      }
    });

    /** Holding checkUpdateAll */
    Composite bottomHolder = new Composite(proxyGroup, SWT.NONE);
    bottomHolder.setLayoutData(LayoutDataShop.createGridData(GridData.FILL_HORIZONTAL, 2));
    bottomHolder.setLayout(new GridLayout(2, false));

    /** Update all favorits label */
    checkUpdateAll = new Button(bottomHolder, SWT.CHECK);
    checkUpdateAll.setLayoutData(LayoutDataShop.createGridData(GridData.FILL_HORIZONTAL, 2));
    checkUpdateAll.setFont(dialogFont);
    checkUpdateAll.setText(GUI.i18n.getTranslation("LABEL_USE_PROXY_FOR_ALL"));
    checkUpdateAll.setSelection(propertyChangeManager.isUpdateProxyForAllFavorites());

    /** Enable / Disable Components */
    if (propertyChangeManager.getProxySettingsSave().get("proxySet").equals("false"))
      setEnabledComponents(false);
    else
      checkUseProxy.setSelection(true);

    /** Enable / Disable Components */
    if (propertyChangeManager.getProxySettingsSave().get("username").equals("") && propertyChangeManager.getProxySettingsSave().get("password").equals(""))
      disableAuthentification();
    else
      checkUseAuthentification.setSelection(true);

    /** Group holding the connection count settings */
    Group connectionCountGroup = new Group(composite, SWT.NONE);
    connectionCountGroup.setLayoutData(LayoutDataShop.createGridData(GridData.VERTICAL_ALIGN_BEGINNING | GridData.FILL_HORIZONTAL, 2));
    connectionCountGroup.setText(GUI.i18n.getTranslation("MENU_MISC"));
    connectionCountGroup.setLayout(LayoutShop.createGridLayout(2, 5, 5, 10));
    connectionCountGroup.setFont(FontShop.dialogFont);

    /** Connection Count Label */
    Label labelConCount = new Label(connectionCountGroup, SWT.NONE);
    labelConCount.setText(GUI.i18n.getTranslation("LABEL_MAX_CONNECTIONS") + ": ");
    labelConCount.setFont(dialogFont);
    labelConCount.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_CENTER | GridData.HORIZONTAL_ALIGN_BEGINNING));

    /** Spinner to set number of connections */
    conCountSpinner = new Spinner(connectionCountGroup, SWT.BORDER);
    conCountSpinner.setMinimum(MIN_CONNECTION_COUNT);
    conCountSpinner.setMaximum(MAX_CONNECTION_COUNT);
    conCountSpinner.setSelection(propertyChangeManager.getMaxConnectionCount());
    conCountSpinner.setFont(FontShop.dialogFont);
    conCountSpinner.setLayoutData(LayoutDataShop.createGridData(GridData.HORIZONTAL_ALIGN_BEGINNING, 1));

    /** Connection Timeout Label */
    Label labelConTimeout = new Label(connectionCountGroup, SWT.NONE);
    labelConTimeout.setText(GUI.i18n.getTranslation("LABEL_CON_TIMEOUT") + ": ");
    labelConTimeout.setFont(dialogFont);
    labelConTimeout.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_CENTER | GridData.HORIZONTAL_ALIGN_BEGINNING));

    /** Spinner to set connection timeout */
    conTimeoutSpinner = new Spinner(connectionCountGroup, SWT.BORDER);
    conTimeoutSpinner.setMinimum(MIN_CONNECTION_TIMEOUT);
    conTimeoutSpinner.setMaximum(MAX_CONNECTION_TIMEOUT);
    conTimeoutSpinner.setSelection(propertyChangeManager.getConnectionTimeout());
    conTimeoutSpinner.setFont(FontShop.dialogFont);
    conTimeoutSpinner.setLayoutData(LayoutDataShop.createGridData(GridData.HORIZONTAL_ALIGN_BEGINNING, 1));

    /** Set Mnemonics to Buttons */
    WidgetShop.initMnemonics(new Button[] { checkUseProxy, checkUseAuthentification, checkUpdateAll });
  }

  /**
   * @see net.sourceforge.rssowl.controller.properties.PropertyPage#restoreButtonPressed()
   */
  protected void restoreButtonPressed() {
    checkUseProxy.setSelection(false);
    setEnabledComponents(false);
    checkUpdateAll.setSelection(true);
    conCountSpinner.setSelection(32);
    conTimeoutSpinner.setSelection(30);
    updatePropertiesChangeManager();
  }

  /**
   * Enable / Disable components for Proxy GlobalSettings Edit
   * 
   * @param enabled TRUE to enable the components
   */
  void setEnabledComponents(boolean enabled) {
    textHost.setEnabled(enabled);
    textPort.setEnabled(enabled);
    checkUseProxy.setSelection(enabled);
    checkUseAuthentification.setEnabled(enabled);
    checkUpdateAll.setEnabled(enabled);

    /** Disable Username and Password fields */
    if (!enabled) {
      textUsername.setEnabled(enabled);
      textPassword.setEnabled(enabled);
      textDomain.setEnabled(enabled);
    }

    /** Enable Username and Password fields */
    else if (checkUseAuthentification.getSelection()) {
      textUsername.setEnabled(true);
      textPassword.setEnabled(true);
      textDomain.setEnabled(true);
    }
  }
}