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

import java.util.ArrayList;

/**
 * Class displays a PropertyPage to set the sort order that RSSOwl should use
 * for all feeds.
 * 
 * @author <a href="mailto:bpasero@rssowl.org">Benjamin Pasero </a>
 * @version 1.2.3
 */
public class SortOrderPropertiers extends PropertyPage {
  Button doNotSortCheck;
  Button downButton;
  List sortOrderList;
  Button upButton;

  /**
   * Instatiate a new SortOrderProperties PropertyPage
   * 
   * @param parent Composite's parent
   */
  public SortOrderPropertiers(Composite parent) {
    super(parent);
  }

  /**
   * @see net.sourceforge.rssowl.controller.properties.PropertyPage#applyButtonPressed()
   */
  public void applyButtonPressed() {
    GlobalSettings.sortOrder = listToArrayList();
    GlobalSettings.autoSortNews = !doNotSortCheck.getSelection();
    updatePropertiesChangeManager();
  }

  /**
   * @see net.sourceforge.rssowl.controller.properties.PropertyPage#updatePropertiesChangeManager()
   */
  public void updatePropertiesChangeManager() {
    propertyChangeManager.setSortOrder(listToArrayList());
    propertyChangeManager.setAutoSortNews(!doNotSortCheck.getSelection());
  }

  /**
   * Create a ArrayList from the sort order list
   * 
   * @return ArrayList All items from the list
   */
  private ArrayList listToArrayList() {
    ArrayList sortOrder = new ArrayList();
    String[] items = sortOrderList.getItems();
    for (int a = 0; a < items.length; a++)
      sortOrder.add(sortOrderList.getData(items[a]));
    return sortOrder;
  }

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

    /** Group for the mail body */
    Group explanationGroup = new Group(composite, SWT.NONE);
    explanationGroup.setText(GUI.i18n.getTranslation("LABEL_DESCRIPTION"));
    explanationGroup.setLayoutData(LayoutDataShop.createGridData(GridData.FILL_HORIZONTAL, 2));
    explanationGroup.setLayout(new GridLayout(1, false));
    explanationGroup.setFont(FontShop.dialogFont);

    /** Explanation label */
    Label explanation = new Label(explanationGroup, SWT.WRAP);
    explanation.setText(GUI.i18n.getTranslation("LABEL_SORT_EXPLANATION"));
    explanation.setFont(dialogFont);
    explanation.setLayoutData(new GridData(GridData.FILL_BOTH));

    /** List displaying the sort order items */
    sortOrderList = new List(composite, SWT.SINGLE | SWT.BORDER);
    sortOrderList.setFont(dialogFont);
    sortOrderList.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
    sortOrderList.addSelectionListener(new SelectionAdapter() {
      public void widgetSelected(SelectionEvent e) {
        upButton.setEnabled(true);
        downButton.setEnabled(true);
      }
    });

    /** Fill the list with the sorting order */
    ArrayList sortOrderState = propertyChangeManager.getSortOrder();
    for (int a = 0; a < sortOrderState.size(); a++) {
      String sortOrderItem = (String) sortOrderState.get(a);
      sortOrderList.add(GUI.i18n.getTranslation(sortOrderItem));
      sortOrderList.setData(GUI.i18n.getTranslation(sortOrderItem), sortOrderItem);
    }

    /** Holder for the up and down buttons */
    Composite buttonHolder = new Composite(composite, SWT.NONE);
    buttonHolder.setLayout(LayoutShop.createGridLayout(1, 0, 0, false));
    buttonHolder.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING));

    /** Button to move an listeitem up */
    upButton = new Button(buttonHolder, SWT.NONE);
    upButton.setFont(dialogFont);
    upButton.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING));
    upButton.setText(GUI.i18n.getTranslation("BUTTON_UP"));
    upButton.addSelectionListener(new SelectionAdapter() {
      public void widgetSelected(SelectionEvent e) {
        moveListElementUp();
      }
    });

    /** Button to move an listitem down */
    downButton = new Button(buttonHolder, SWT.NONE);
    downButton.setFont(dialogFont);
    downButton.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING));
    downButton.setText(GUI.i18n.getTranslation("BUTTON_DOWN"));
    downButton.addSelectionListener(new SelectionAdapter() {
      public void widgetSelected(SelectionEvent e) {
        moveListElementDown();
      }
    });

    /** Apply layout data to buttons */
    setButtonLayoutData(upButton, new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING));
    setButtonLayoutData(downButton, new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING));

    /** Check Button to disable auto-sorting */
    doNotSortCheck = new Button(composite, SWT.CHECK);
    doNotSortCheck.setFont(dialogFont);
    doNotSortCheck.setText(GUI.i18n.getTranslation("BUTTON_NO_SORT"));
    doNotSortCheck.setSelection(!propertyChangeManager.isAutoSortNews());

    /** Disable sort order list when this checkbutton is selected */
    doNotSortCheck.addSelectionListener(new SelectionAdapter() {
      public void widgetSelected(SelectionEvent e) {
        setAutoSortControlsState(!doNotSortCheck.getSelection());
        sortOrderList.deselectAll();
      }
    });

    /** Set state of sort order controlls */
    setAutoSortControlsState(!doNotSortCheck.getSelection());

    /** Set some spacer */
    LayoutShop.setDialogSpacer(composite, 2, 4);

    /** Set Mnemonics to Buttons */
    WidgetShop.initMnemonics(new Button[] { upButton, downButton, doNotSortCheck });
  }

  /**
   * @see net.sourceforge.rssowl.controller.properties.PropertyPage#restoreButtonPressed()
   */
  protected void restoreButtonPressed() {
    String[] defaultSortOrder = GlobalSettings.defaultSortOrder;
    sortOrderList.removeAll();

    /** Fill default sort order into List */
    for (int a = 0; a < defaultSortOrder.length; a++) {
      String sortOrderItem = defaultSortOrder[a];
      sortOrderList.add(GUI.i18n.getTranslation(sortOrderItem));
      sortOrderList.setData(GUI.i18n.getTranslation(sortOrderItem), sortOrderItem);
    }
    doNotSortCheck.setSelection(false);
    setAutoSortControlsState(true);
  }

  /**
   * Replace the selected item with the item beyond it.
   */
  void moveListElementDown() {
    int index[] = sortOrderList.getSelectionIndices();

    /** There must be a selection and an item beyond the selection */
    if (index.length == 1 && index[0] != (sortOrderList.getItemCount() - 1)) {
      String selection = sortOrderList.getItem(index[0]);
      String target = sortOrderList.getItem(index[0] + 1);
      sortOrderList.setItem(index[0], target);
      sortOrderList.setItem(index[0] + 1, selection);
      sortOrderList.setSelection(index[0] + 1);
    }
  }

  /**
   * Replace the selected item with the item above it.
   */
  void moveListElementUp() {
    int index[] = sortOrderList.getSelectionIndices();

    /** There must be a selection and an item above the selection */
    if (index.length == 1 && index[0] != 0) {
      String selection = sortOrderList.getItem(index[0]);
      String target = sortOrderList.getItem(index[0] - 1);
      sortOrderList.setItem(index[0], target);
      sortOrderList.setItem(index[0] - 1, selection);
      sortOrderList.setSelection(index[0] - 1);
    }
  }

  /**
   * Enable / Disable the sort order list and the buttons
   * 
   * @param enabled If TRUE controls become enabled, otherwise disabled
   */
  void setAutoSortControlsState(boolean enabled) {
    sortOrderList.setEnabled(enabled);
    upButton.setEnabled(enabled && sortOrderList.getSelectionCount() != 0);
    downButton.setEnabled(enabled && sortOrderList.getSelectionCount() != 0);
  }
}