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

import net.sourceforge.rssowl.controller.EventManager;
import net.sourceforge.rssowl.controller.GUI;
import net.sourceforge.rssowl.model.Category;
import net.sourceforge.rssowl.model.TreeItemData;
import net.sourceforge.rssowl.util.GlobalSettings;
import net.sourceforge.rssowl.util.shop.PaintShop;
import net.sourceforge.rssowl.util.shop.ProxyShop;
import net.sourceforge.rssowl.util.shop.WidgetShop;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MenuAdapter;
import org.eclipse.swt.events.MenuEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TreeItem;

/**
 * The blogroll-category popup appears when right-clicking on any category that
 * is part of a blogroll in the tree.
 * 
 * @author <a href="mailto:bpasero@rssowl.org">Benjamin Pasero </a>
 * @version 1.2.3
 */
public class BlogrollCategoryPopup {
  private Menu popUpMenu;
  private Shell shell;
  EventManager eventManager;
  GUI rssOwlGui;
  TreeItem selectedTreeItem;

  /**
   * Instantiate a new BlogrollCategoryPopup
   * 
   * @param shell The shell
   * @param rssOwlGui The maincontroller
   * @param popUpMenu The menu to add this menu to
   * @param eventManager The event manager
   * @param selectedTreeItem The treeitem that gets this menu
   */
  public BlogrollCategoryPopup(Shell shell, GUI rssOwlGui, Menu popUpMenu, EventManager eventManager, TreeItem selectedTreeItem) {
    this.shell = shell;
    this.rssOwlGui = rssOwlGui;
    this.popUpMenu = popUpMenu;
    this.eventManager = eventManager;
    this.selectedTreeItem = selectedTreeItem;

    /** Init the Popup */
    initBlogrollCategoryMenu();
  }

  /** Init the popup menuStructure for a blogroll category */
  private void initBlogrollCategoryMenu() {

    /** Aggregate selected category */
    MenuItem open = new MenuItem(popUpMenu, SWT.PUSH);
    open.setText(GUI.i18n.getTranslation("POP_AGGREGATE_FAV"));
    open.addSelectionListener(new SelectionAdapter() {
      public void widgetSelected(SelectionEvent e) {
        eventManager.actionAggregateCategory(false);
      }
    });

    /** Disable this menuitem if treeitem has no childs */
    if (selectedTreeItem.getItemCount() <= 0)
      open.setEnabled(false);

    /** Open selected categorie's direct Favorites */
    if (!GlobalSettings.displaySingleTab) {
      boolean enabled = false;

      MenuItem openCategory = new MenuItem(popUpMenu, SWT.PUSH);
      openCategory.setText(GUI.i18n.getTranslation("BUTTON_OPEN"));
      openCategory.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent e) {
          eventManager.actionOpenSelectedCategory();
        }
      });

      /** Disable this menuitem if treeitem has no direct Favorites */
      TreeItem childs[] = selectedTreeItem.getItems();
      for (int i = 0; i < childs.length; i++) {
        TreeItem item = childs[i];
        if (item.getData() != null && ((TreeItemData) item.getData()).isBlogrollFavorite()) {
          enabled = true;
          break;
        }
      }

      if (!enabled)
        openCategory.setEnabled(false);
    }

    /** Separator */
    new MenuItem(popUpMenu, SWT.SEPARATOR);

    /** Mark selected category read */
    MenuItem markRead = new MenuItem(popUpMenu, SWT.PUSH);
    markRead.setText(GUI.i18n.getTranslation("POP_MARK_CATEGORY_READ"));
    markRead.addSelectionListener(new SelectionAdapter() {
      public void widgetSelected(SelectionEvent e) {
        eventManager.actionMarkCategoryRead();
      }
    });

    /** Disable this menuitem if treeitem has no childs */
    if (selectedTreeItem.getItemCount() <= 0)
      markRead.setEnabled(false);

    /** Separator */
    new MenuItem(popUpMenu, SWT.SEPARATOR);

    /** Reload all favorites of the selected category */
    MenuItem reload = new MenuItem(popUpMenu, SWT.PUSH);
    reload.setText(GUI.i18n.getTranslation("BUTTON_RELOAD_CAT"));
    if (!GlobalSettings.isMac())
      reload.setImage(PaintShop.iconReload);
    reload.addSelectionListener(new SelectionAdapter() {
      public void widgetSelected(SelectionEvent e) {
        eventManager.actionAggregateCategory(true);
      }
    });

    /** Disable this menuitem if treeitem has no childs */
    if (selectedTreeItem.getItemCount() <= 0)
      reload.setEnabled(false);

    /** Separator */
    new MenuItem(popUpMenu, SWT.SEPARATOR);

    /** Search in all favorites of the selected category */
    MenuItem search = new MenuItem(popUpMenu, SWT.PUSH);
    search.setText(GUI.i18n.getTranslation("SEARCH_DIALOG_TITLE") + "...");
    if (!GlobalSettings.isMac())
      search.setImage(PaintShop.iconFind);
    search.addSelectionListener(new SelectionAdapter() {
      public void widgetSelected(SelectionEvent e) {
        eventManager.actionSearchInCategory();
      }
    });

    /** Disable this menuitem if treeitem has no childs */
    if (selectedTreeItem.getItemCount() <= 0)
      search.setEnabled(false);

    /** Separator */
    new MenuItem(popUpMenu, SWT.SEPARATOR);

    /** Check wether creation of a Category is allowed */
    boolean isNewCategoryAllowed = true;
    TreeItem parent = selectedTreeItem.getParentItem();
    if (WidgetShop.isset(parent) && parent.getData() != null) {
      TreeItemData data = (TreeItemData) parent.getData();
      if (data.isBlogroll())
        isNewCategoryAllowed = false;
    }

    /** New Menu - If allowed */
    if (isNewCategoryAllowed) {
      MenuItem newCatOrFav = new MenuItem(popUpMenu, SWT.CASCADE);
      newCatOrFav.setText(GUI.i18n.getTranslation("POP_NEW"));

      Menu selectNewCatOrFav = new Menu(shell, SWT.DROP_DOWN);
      newCatOrFav.setMenu(selectNewCatOrFav);
      if (!GlobalSettings.isMac())
        newCatOrFav.setImage(PaintShop.iconNew);

      /** Create a new category */
      MenuItem cascadeItemNewCat = new MenuItem(selectNewCatOrFav, SWT.PUSH);
      cascadeItemNewCat.setText(GUI.i18n.getTranslation("LABEL_CATEGORY") + "...");
      if (!GlobalSettings.isMac())
        cascadeItemNewCat.setImage(PaintShop.iconAddCategory);
      cascadeItemNewCat.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent e) {
          eventManager.actionNewCategory(false);
        }
      });
    }

    /** Synchronize */
    MenuItem synchronize = new MenuItem(popUpMenu, SWT.PUSH);
    synchronize.setText(GUI.i18n.getTranslation("POP_SYNCHRONIZE"));
    synchronize.addSelectionListener(new SelectionAdapter() {
      public void widgetSelected(SelectionEvent e) {
        eventManager.actionSynchronizeBlogroll();
      }
    });

    /** Unsubscribe */
    MenuItem remove = new MenuItem(popUpMenu, SWT.PUSH);
    remove.setText(GUI.i18n.getTranslation("POP_UNSUBSCRIBE"));
    if (!GlobalSettings.isMac())
      remove.setImage(PaintShop.iconDelete);
    remove.addSelectionListener(new SelectionAdapter() {
      public void widgetSelected(SelectionEvent e) {
        eventManager.actionDeleteBlogroll();
      }
    });

    /** Separator */
    new MenuItem(popUpMenu, SWT.SEPARATOR);

    /** Copy URL of the blogroll */
    MenuItem copyXmlLocation = new MenuItem(popUpMenu, SWT.PUSH);
    copyXmlLocation.setText(GUI.i18n.getTranslation("POP_COPY_NEWS_URL"));
    copyXmlLocation.addSelectionListener(new SelectionAdapter() {
      public void widgetSelected(SelectionEvent e) {
        eventManager.actionCopyBlogrollXmlLocation();
      }
    });

    /** Separator */
    new MenuItem(popUpMenu, SWT.SEPARATOR);

    /** Import OPML files */
    MenuItem importMenu = new MenuItem(popUpMenu, SWT.CASCADE);
    importMenu.setText(GUI.i18n.getTranslation("POP_IMPORT"));
    if (!GlobalSettings.isMac())
      importMenu.setImage(PaintShop.iconImport);

    Menu selectImport = new Menu(shell, SWT.DROP_DOWN);
    importMenu.setMenu(selectImport);

    /** Import OPML */
    MenuItem cascadeItemImportOPML = new MenuItem(selectImport, SWT.PUSH);
    cascadeItemImportOPML.setText(GUI.i18n.getTranslation("POP_FROM_OPML") + "...");
    if (!GlobalSettings.isMac())
      cascadeItemImportOPML.setImage(PaintShop.iconImportOpml);
    cascadeItemImportOPML.addSelectionListener(new SelectionAdapter() {
      public void widgetSelected(SelectionEvent e) {
        eventManager.actionImportOPML();
      }
    });

    /** Import Synchronized Blogroll */
    MenuItem cascadeItemImportBlogroll = new MenuItem(selectImport, SWT.PUSH);
    cascadeItemImportBlogroll.setText(GUI.i18n.getTranslation("POP_IMPORT_BLOGROLL") + "...");
    if (!GlobalSettings.isMac())
      cascadeItemImportBlogroll.setImage(PaintShop.iconAddBlogroll);
    cascadeItemImportBlogroll.addSelectionListener(new SelectionAdapter() {
      public void widgetSelected(SelectionEvent e) {
        eventManager.actionImportBlogroll();
      }
    });

    /** Export to OPML file */
    MenuItem export = new MenuItem(popUpMenu, SWT.CASCADE);
    export.setText(GUI.i18n.getTranslation("BUTTON_EXPORT"));
    if (!GlobalSettings.isMac())
      export.setImage(PaintShop.iconExport);

    /** Disable this menuitem if treeitem has no childs */
    if (selectedTreeItem.getItemCount() <= 0)
      export.setEnabled(false);

    Menu selectexport = new Menu(shell, SWT.DROP_DOWN);
    export.setMenu(selectexport);

    MenuItem cascadeItemCreateOPML = new MenuItem(selectexport, SWT.PUSH);
    cascadeItemCreateOPML.setText(GUI.i18n.getTranslation("POP_EXPORT_OPML") + "...");
    if (!GlobalSettings.isMac())
      cascadeItemCreateOPML.setImage(PaintShop.iconExportOpml);
    cascadeItemCreateOPML.addSelectionListener(new SelectionAdapter() {
      public void widgetSelected(SelectionEvent e) {
        eventManager.actionCategoryToOPML();
      }
    });

    /** In case Proxy is activated */
    if (ProxyShop.isUseProxy()) {

      /** Separator */
      new MenuItem(popUpMenu, SWT.SEPARATOR);

      /** Enable / Disable use of proxy */
      MenuItem proxy = new MenuItem(popUpMenu, SWT.CASCADE);
      proxy.setText(GUI.i18n.getTranslation("MENU_PROXY"));

      Menu selectProxy = new Menu(shell, SWT.DROP_DOWN);
      proxy.setMenu(selectProxy);

      final MenuItem cascadeItemProxy = new MenuItem(selectProxy, SWT.CHECK);
      cascadeItemProxy.setText(GUI.i18n.getTranslation("POP_USEPROXY"));
      cascadeItemProxy.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent e) {
          if (cascadeItemProxy.isEnabled())
            eventManager.actionSetProxyOnTreeItem(cascadeItemProxy.getSelection());
        }
      });

      /** Dynamically react on the Proxy Settings */
      selectProxy.addMenuListener(new MenuAdapter() {
        public void menuShown(MenuEvent e) {
          Category selectedCat = rssOwlGui.getRSSOwlFavoritesTree().getSelectedCat();

          if (selectedCat != null)
            cascadeItemProxy.setSelection(selectedCat.isUseProxy());
        }
      });
    }

    /** Separator */
    new MenuItem(popUpMenu, SWT.SEPARATOR);

    /** Edit selected blogroll */
    MenuItem properties = new MenuItem(popUpMenu, SWT.PUSH);
    properties.setText(GUI.i18n.getTranslation("POP_PROPERTIES"));
    properties.addSelectionListener(new SelectionAdapter() {
      public void widgetSelected(SelectionEvent e) {
        eventManager.actionEditBlogroll();
      }
    });
  }
}