/*   **********************************************************************  **
 **   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.controller.thread.AmphetaRateThread;
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.StringShop;
import net.sourceforge.rssowl.util.shop.WidgetShop;

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CLabel;
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.Text;

import java.io.IOException;

/**
 * Class displays a PropertyPage to configure AmphetaRate in RSSOwl
 * 
 * @author <a href="mailto:bpasero@rssowl.org">Benjamin Pasero </a>
 * @version 1.2.3
 */
public class AmphetaRateProperties extends PropertyPage {
  private Group existingAccountGroup;
  private Composite existingAccountHolder;
  private Text password;
  private Label userIDLabel;
  private Text username;
  Text userId;

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

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

    /** This is and old user, no changes possible except for creating a new user */
    if (AmphetaRateThread.isOldUser())
      return;

    /** Changes made to username and / or password */
    if (!GlobalSettings.amphetaRateUsername.equals(username.getText()) || !GlobalSettings.amphetaRatePassword.equals(password.getText())) {
      GlobalSettings.amphetaRateUsername = username.getText();
      GlobalSettings.amphetaRatePassword = password.getText();

      /** Update AmphetaRate ToolBar */
      rssOwlGui.getRSSOwlNewsText().setNewsTextToolBarVisible(StringShop.isset(GlobalSettings.amphetaRateUsername));
      rssOwlGui.getRSSOwlStatusLine().setAmphetaRateItemsVisible(StringShop.isset(GlobalSettings.amphetaRateUsername));

      /** Update the AmphetaRate recommendation feed */
      rssOwlGui.getRSSOwlFavoritesTree().createAmphetaRateFeed();
    }
    updatePropertiesChangeManager();
  }

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

    /** This is and old user, no changes possible except for creating a new user */
    if (AmphetaRateThread.isOldUser())
      return;

    propertyChangeManager.setAmphetaRateUsername(username.getText());
    propertyChangeManager.setAmphetaRatePassword(password.getText());
  }

  /** Init all components */
  protected void initComponents() {

    /** Group for the custom browser path components */
    existingAccountGroup = new Group(composite, SWT.NONE);
    existingAccountGroup.setLayoutData(LayoutDataShop.createGridData(GridData.VERTICAL_ALIGN_BEGINNING | GridData.FILL_HORIZONTAL, 2));
    existingAccountGroup.setText(GUI.i18n.getTranslation("GROUP_EXISTING_ACCOUNT"));
    existingAccountGroup.setLayout(new GridLayout(2, false));
    existingAccountGroup.setFont(FontShop.dialogFont);

    /** Dynamically set contents of the group */
    createExistingAccountGroup(!GlobalSettings.amphetaRateUserID.equals(""));

    /** Group for to create a new AmphetaRate user */
    Group newAccountGroup = new Group(composite, SWT.NONE);
    newAccountGroup.setLayoutData(LayoutDataShop.createGridData(GridData.VERTICAL_ALIGN_BEGINNING | GridData.FILL_HORIZONTAL, 2));
    newAccountGroup.setText(GUI.i18n.getTranslation("GROUP_NEW_ACCOUNT"));
    newAccountGroup.setLayout(new GridLayout(2, false));
    newAccountGroup.setFont(FontShop.dialogFont);

    /** New Username label */
    Label newUsernameLabel = new Label(newAccountGroup, SWT.NONE);
    newUsernameLabel.setText(GUI.i18n.getTranslation("LABEL_USERNAME") + ": ");
    newUsernameLabel.setLayoutData(LayoutDataShop.createGridData(GridData.HORIZONTAL_ALIGN_BEGINNING, 1));
    newUsernameLabel.setFont(dialogFont);

    /** Input for the Username */
    final Text newUsernameInput = new Text(newAccountGroup, SWT.SINGLE | SWT.BORDER);
    newUsernameInput.setLayoutData(LayoutDataShop.createGridData(GridData.FILL_HORIZONTAL, 1));
    newUsernameInput.setFont(dialogFont);

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

    /** New password label */
    Label newPasswordLabel = new Label(newAccountGroup, SWT.NONE);
    newPasswordLabel.setText(GUI.i18n.getTranslation("LABEL_PASSWORD") + ": ");
    newPasswordLabel.setLayoutData(LayoutDataShop.createGridData(GridData.HORIZONTAL_ALIGN_BEGINNING, 1));
    newPasswordLabel.setFont(dialogFont);

    /** Input for the Password */
    final Text newPasswordInput = new Text(newAccountGroup, SWT.SINGLE | SWT.BORDER | SWT.PASSWORD);
    newPasswordInput.setLayoutData(LayoutDataShop.createGridData(GridData.FILL_HORIZONTAL, 1));
    newPasswordInput.setFont(dialogFont);

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

    /** Optional old id label */
    Label oldIdLabel = new Label(newAccountGroup, SWT.NONE);
    oldIdLabel.setText(GUI.i18n.getTranslation("LABEL_OLD_ID") + ": ");
    oldIdLabel.setLayoutData(LayoutDataShop.createGridData(GridData.HORIZONTAL_ALIGN_BEGINNING, 1));
    oldIdLabel.setFont(dialogFont);

    /** Input for the old AmphetaRate User ID */
    final Text oldIdInput = new Text(newAccountGroup, SWT.SINGLE | SWT.BORDER);
    oldIdInput.setLayoutData(LayoutDataShop.createGridData(GridData.FILL_HORIZONTAL, 1));
    oldIdInput.setFont(dialogFont);
    oldIdInput.setText(propertyChangeManager.getAmphetaRateId());

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

    /** Button to create a new user */
    Button createAccountButton = new Button(newAccountGroup, SWT.NONE);
    createAccountButton.setText(GUI.i18n.getTranslation("BUTTON_CREATE_ACCOUNT"));
    createAccountButton.setFont(dialogFont);

    /** Apply layout data to Button */
    setButtonLayoutData(createAccountButton, LayoutDataShop.createGridData(GridData.HORIZONTAL_ALIGN_END, 2));

    /** Create Account on Click */
    createAccountButton.addSelectionListener(new SelectionAdapter() {
      public void widgetSelected(SelectionEvent e) {

        /** Reset error message */
        setErrorMessage(null);

        /** Create a new unique AmphetaRate user */
        try {

          /** Data that the user has typed in */
          String user = newUsernameInput.getText();
          String password = newPasswordInput.getText();
          String oldId = oldIdInput.getText();

          /** Do nothing if username is empty */
          if (user.equals(""))
            return;

          /** Show Wait Cursor */
          composite.getShell().setCursor(GUI.display.getSystemCursor(SWT.CURSOR_WAIT));

          /** Register and retrieve status from server */
          String status = AmphetaRateThread.register(user, password, oldId);

          /** Account created successfully */
          if (status.indexOf(AmphetaRateThread.STATUS_OK) >= 0) {

            /** Update property manager */
            propertyChangeManager.setAmphetaRateUsername(user);
            propertyChangeManager.setAmphetaRatePassword(password);
            propertyChangeManager.setAmphetaRateId("");

            /** Mark this user a new user deleting a possible old user id */
            GlobalSettings.amphetaRateUserID = "";

            /** Update top group */
            createExistingAccountGroup(false);

            /** Clear form */
            newUsernameInput.setText("");
            newPasswordInput.setText("");
            oldIdInput.setText("");

            /** Show success message */
            setSuccessMessage(GUI.i18n.getTranslation("LABEL_REGISTRATION_SUCCESS"));
          }

          /** There was an error, show it */
          else {
            setErrorMessage(status);
          }
        }

        /** Give out a connection failed warning */
        catch (IOException ex) {
          setErrorMessage(GUI.i18n.getTranslation("ERROR_CONNECTION_FAILED"));
          GUI.logger.log("AmphetaRateThread.register()", ex);
        }

        /** Restore Cursor */
        finally {
          composite.getShell().setCursor(null);
        }
      }
    });

    /** Error label */
    errorMessageLabel = new CLabel(newAccountGroup, SWT.NONE);
    errorMessageLabel.setFont(dialogFont);
    errorMessageLabel.setLayoutData(LayoutDataShop.createGridData(GridData.HORIZONTAL_ALIGN_BEGINNING, 2));

    /** Set Mnemonics to Buttons */
    WidgetShop.initMnemonics(new Button[] { createAccountButton });
  }

  /**
   * This property page does not support the restore action. The restore button
   * is disabled.
   */
  protected void restoreButtonPressed() {
  // Not necessary
  }

  /**
   * Dynamically create the contents of this group. If the user has an existing
   * AmphetaRate user id it is displayed in a readonly input field indicating
   * that he should update his account to one with username and password. In the
   * other case, input fields for username and password are displayed.
   * 
   * @param isOldUser TRUE if the user has an old AmphetaRate user id
   */
  void createExistingAccountGroup(boolean isOldUser) {

    /** Update contents */
    if (WidgetShop.isset(existingAccountHolder))
      existingAccountHolder.dispose();

    /** Composite to easily renew following controlls */
    existingAccountHolder = new Composite(existingAccountGroup, SWT.NONE);
    existingAccountHolder.setLayoutData(LayoutDataShop.createGridData(GridData.VERTICAL_ALIGN_BEGINNING | GridData.FILL_HORIZONTAL, 2));
    existingAccountHolder.setLayout(new GridLayout(2, false));

    /** This is an old, existing user. Display the User ID */
    if (isOldUser) {

      /** User ID label */
      userIDLabel = new Label(existingAccountHolder, SWT.NONE);
      userIDLabel.setText(GUI.i18n.getTranslation("LABEL_AMPHETARATE_ID") + ": ");
      userIDLabel.setLayoutData(LayoutDataShop.createGridData(GridData.HORIZONTAL_ALIGN_BEGINNING, 1));
      userIDLabel.setFont(dialogFont);

      /** Input for the AmphetaRate User ID */
      userId = new Text(existingAccountHolder, SWT.SINGLE | SWT.BORDER | SWT.READ_ONLY);
      userId.setLayoutData(LayoutDataShop.createGridData(GridData.FILL_HORIZONTAL, 1));
      userId.setFont(dialogFont);
      userId.setText(propertyChangeManager.getAmphetaRateId());

      /** Tweak Text Widget */
      WidgetShop.tweakTextWidget(userId);
    }

    /** The user is either new or has not created an account yet */
    else {

      /** Username label */
      Label usernameLabel = new Label(existingAccountHolder, SWT.NONE);
      usernameLabel.setText(GUI.i18n.getTranslation("LABEL_USERNAME") + ": ");
      usernameLabel.setLayoutData(LayoutDataShop.createGridData(GridData.HORIZONTAL_ALIGN_BEGINNING, 1));
      usernameLabel.setFont(dialogFont);

      /** Input for the AmphetaRate Username */
      username = new Text(existingAccountHolder, SWT.SINGLE | SWT.BORDER);
      username.setLayoutData(LayoutDataShop.createGridData(GridData.FILL_HORIZONTAL, 1));
      username.setFont(dialogFont);
      username.setText(propertyChangeManager.getAmphetaRateUsername());

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

      /** Password label */
      Label passwordLabel = new Label(existingAccountHolder, SWT.NONE);
      passwordLabel.setText(GUI.i18n.getTranslation("LABEL_PASSWORD") + ": ");
      passwordLabel.setLayoutData(LayoutDataShop.createGridData(GridData.HORIZONTAL_ALIGN_BEGINNING, 1));
      passwordLabel.setFont(dialogFont);

      /** Input for the AmphetaRate Password */
      password = new Text(existingAccountHolder, SWT.SINGLE | SWT.BORDER | SWT.PASSWORD);
      password.setLayoutData(LayoutDataShop.createGridData(GridData.FILL_HORIZONTAL, 1));
      password.setFont(dialogFont);
      password.setText(propertyChangeManager.getAmphetaRatePassword());

      /** Tweak Text Widget */
      WidgetShop.tweakTextWidget(password);
    }

    /** Layout group */
    existingAccountGroup.layout();
    composite.layout();
  }
}