com.charlie.client.panels.SonglistPanel.java Source code

Java tutorial

Introduction

Here is the source code for com.charlie.client.panels.SonglistPanel.java

Source

/* 
 * Ext GWT - Ext for GWT 
 * Copyright(c) 2007-2009, Ext JS, LLC. 
 * licensing@extjs.com 
 *  
 * http://extjs.com/license 
 */
package com.charlie.client.panels;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import com.allen_sauer.gwt.log.client.Log;
import com.charlie.client.Controller;
import com.charlie.client.HandlesEvents;
import com.charlie.client.components.MP3PlayerInfo;
import com.charlie.client.components.PlaylistSearchComponent;
import com.charlie.client.components.dialogs.EditSongInfoDialog;
import com.charlie.client.components.dialogs.ShowUsersForCollectedSongDialog;
import com.charlie.client.eventbus.EventType;
import com.charlie.client.eventbus.events.AddPlaylistEvent;
import com.charlie.client.eventbus.events.AddSongToPlaylistEvent;
import com.charlie.client.eventbus.events.ArtistInfoEvent;
import com.charlie.client.eventbus.events.ArtistPhotosEvent;
import com.charlie.client.eventbus.events.EditPlaylistEvent;
import com.charlie.client.eventbus.events.EditPlaylistEventHandler;
import com.charlie.client.eventbus.events.GetCollectiveSongsForUserAndAllFriendsEvent;
import com.charlie.client.eventbus.events.GetCollectiveSongsForUserAndAllFriendsEventHandler;
import com.charlie.client.eventbus.events.GetCollectiveSongsForUserEvent;
import com.charlie.client.eventbus.events.GetCollectiveSongsForUserEventHandler;
import com.charlie.client.eventbus.events.GetFriendsForUserEvent;
import com.charlie.client.eventbus.events.GetRecentlyUploadedSongsFromAllEvent;
import com.charlie.client.eventbus.events.GetRecentlyUploadedSongsFromAllEventHandler;
import com.charlie.client.eventbus.events.GetRecentlyUploadedSongsFromUserAndAllFriendsEvent;
import com.charlie.client.eventbus.events.GetRecentlyUploadedSongsFromUserAndAllFriendsEventHandler;
import com.charlie.client.eventbus.events.GetSongsForAllEvent;
import com.charlie.client.eventbus.events.GetSongsForAllEventHandler;
import com.charlie.client.eventbus.events.GetSongsForUserAndAllFriendsEvent;
import com.charlie.client.eventbus.events.GetSongsForUserAndAllFriendsEventHandler;
import com.charlie.client.eventbus.events.GetSongsForUserEvent;
import com.charlie.client.eventbus.events.GetSongsForUserEventHandler;
import com.charlie.client.eventbus.events.InviteFriendByUserIdEvent;
import com.charlie.client.eventbus.events.PlayPlaylistEvent;
import com.charlie.client.eventbus.events.PlayPlaylistEventHandler;
import com.charlie.client.eventbus.events.PlaySongEvent;
import com.charlie.client.eventbus.events.PlaySongEventHandler;
import com.charlie.client.eventbus.events.PlaylistsListLoadedEvent;
import com.charlie.client.eventbus.events.PlaylistsListLoadedEventHandler;
import com.charlie.client.eventbus.events.PlaylistsNeedReloadingEvent;
import com.charlie.client.eventbus.events.PlaylistsNeedReloadingEventHandler;
import com.charlie.client.eventbus.events.RandomizePlaylistEvent;
import com.charlie.client.eventbus.events.RandomizePlaylistEventHandler;
import com.charlie.client.eventbus.events.RecordEventEvent;
import com.charlie.client.eventbus.events.RemoveAllSongsFromPlaylistEvent;
import com.charlie.client.eventbus.events.RemoveSongFromPlaylistEvent;
import com.charlie.client.eventbus.events.SearchSongsByAlbumFromAllFriendsPagedEvent;
import com.charlie.client.eventbus.events.SearchSongsByAlbumFromAllFriendsPagedEventHandler;
import com.charlie.client.eventbus.events.SearchSongsByArtistFromAllFriendsPagedEvent;
import com.charlie.client.eventbus.events.SearchSongsByArtistFromAllFriendsPagedEventHandler;
import com.charlie.client.eventbus.events.SearchSongsByGenreFromAllFriendsPagedEvent;
import com.charlie.client.eventbus.events.SearchSongsByGenreFromAllFriendsPagedEventHandler;
import com.charlie.client.eventbus.events.SearchSongsByThisAndSimilarArtistsFromAllFriendsPagedEvent;
import com.charlie.client.eventbus.events.SearchSongsByThisAndSimilarArtistsFromAllFriendsPagedEventHandler;
import com.charlie.client.eventbus.events.SearchSongsFromAllFriendsPagedEvent;
import com.charlie.client.eventbus.events.SearchSongsFromAllFriendsPagedEventHandler;
import com.charlie.client.eventbus.events.SearchSongsRandomByThisAndSimilarArtistsFromAllFriendsPagedEvent;
import com.charlie.client.eventbus.events.SearchSongsRandomByThisAndSimilarArtistsFromAllFriendsPagedEventHandler;
import com.charlie.client.eventbus.events.ShowNowPlayingEvent;
import com.charlie.client.eventbus.events.ShowNowPlayingEventHandler;
import com.charlie.client.eventbus.events.SongFinishedLoadingEvent;
import com.charlie.client.eventbus.events.SongFinishedLoadingEventHandler;
import com.charlie.client.eventbus.events.UnrandomizePlaylistEvent;
import com.charlie.client.eventbus.events.UnrandomizePlaylistEventHandler;
import com.charlie.client.modeldata.PlaylistModelData;
import com.charlie.client.modeldata.SongModelData;
import com.charlie.client.services.SiteServiceImpl;
import com.charlie.client.services.SongRetrievalType;
import com.charlie.client.utility.DragDropUtility;
import com.charlie.client.utility.LoadingState;
import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.Style.SortDir;
import com.extjs.gxt.ui.client.data.BasePagingLoadConfig;
import com.extjs.gxt.ui.client.data.BasePagingLoadResult;
import com.extjs.gxt.ui.client.data.BasePagingLoader;
import com.extjs.gxt.ui.client.data.PagingLoadConfig;
import com.extjs.gxt.ui.client.data.PagingLoadResult;
import com.extjs.gxt.ui.client.data.PagingLoader;
import com.extjs.gxt.ui.client.data.RpcProxy;
import com.extjs.gxt.ui.client.dnd.GridDragSource;
import com.extjs.gxt.ui.client.dnd.GridDropTarget;
import com.extjs.gxt.ui.client.dnd.DND.Feedback;
import com.extjs.gxt.ui.client.event.DNDEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.GridEvent;
import com.extjs.gxt.ui.client.event.IconButtonEvent;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.LoadListener;
import com.extjs.gxt.ui.client.event.MenuEvent;
import com.extjs.gxt.ui.client.event.MessageBoxEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.store.GroupingStore;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.store.TreeStoreModel;
import com.extjs.gxt.ui.client.widget.BoxComponent;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.button.IconButton;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnData;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.grid.GridCellRenderer;
import com.extjs.gxt.ui.client.widget.grid.GridGroupRenderer;
import com.extjs.gxt.ui.client.widget.grid.GroupColumnData;
import com.extjs.gxt.ui.client.widget.grid.GroupingView;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.menu.Menu;
import com.extjs.gxt.ui.client.widget.menu.MenuItem;
import com.extjs.gxt.ui.client.widget.menu.SeparatorMenuItem;
import com.extjs.gxt.ui.client.widget.toolbar.PagingToolBar;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.URL;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.DeferredCommand;
import com.google.gwt.user.client.Random;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Anchor;

public class SonglistPanel extends LayoutContainer implements HandlesEvents {

    private static final Integer PAGING_SIZE = 75;
    private Grid<SongModelData> grid = null;
    private ColumnModel columnModel = null;
    private PagingLoader<PagingLoadResult<SongModelData>> loader = null;

    private PagingToolBar pagingToolBar = new PagingToolBar(PAGING_SIZE);
    private ContentPanel contentPanel = null;

    private GroupingStore<SongModelData> store = null;

    private RpcProxy<PagingLoadResult<SongModelData>> proxy = null;
    private PlaylistSearchComponent searchComponent = new PlaylistSearchComponent();
    private ShowUsersForCollectedSongDialog showUsersWhoCollectedSongDialog = new ShowUsersForCollectedSongDialog();
    private EditSongInfoDialog editSongInfoDialog = new EditSongInfoDialog();
    private Menu playlistSubMenu;
    private MenuItem playlistTopLevelMenu;
    PagingLoadConfig pagingLoadConfig = null;

    @SuppressWarnings("unused")
    private GridDragSource dragSource;
    private GridDropTarget target;
    private MenuItem newPlaylist;
    private List<SongModelData> previousSongs = new ArrayList<SongModelData>();
    private ColumnConfig starCountcolumn;

    private IconButton collectButton;
    private IconButton buyButton;
    private Long collectiveUserId = 0L;
    private ColumnConfig totalStarCountColumn;

    public SonglistPanel() {

        addEventHandlers();
        setContextMenu(createContextMenu());

        GridCellRenderer<SongModelData> totalSongCount = new GridCellRenderer<SongModelData>() {

            public Object render(final SongModelData model, String property, ColumnData config, final int rowIndex,
                    final int colIndex, ListStore<SongModelData> store, Grid<SongModelData> grid) {

                Anchor anchor = new Anchor(model.getTotalStarCount().toString());
                anchor.addClickHandler(new ClickHandler() {

                    @Override
                    public void onClick(ClickEvent event) {
                        showUsersWhoCollectedSongDialog.setSongId(model.getSongId());
                        showUsersWhoCollectedSongDialog.showAndLoad();

                    }
                });

                return anchor;

            }
        };

        GridCellRenderer<SongModelData> voteUpButtonRenderer = new GridCellRenderer<SongModelData>() {

            private boolean init;

            public Object render(final SongModelData model, String property, ColumnData config, final int rowIndex,
                    final int colIndex, ListStore<SongModelData> store, Grid<SongModelData> grid) {

                if (!init) {
                    init = true;
                    grid.addListener(Events.ColumnResize, new Listener<GridEvent<SongModelData>>() {

                        public void handleEvent(GridEvent<SongModelData> be) {
                            for (int i = 0; i < be.getGrid().getStore().getCount(); i++) {
                                if (be.getGrid().getView().getWidget(i, be.getColIndex()) != null && be.getGrid()
                                        .getView().getWidget(i, be.getColIndex()) instanceof BoxComponent) {
                                    ((BoxComponent) be.getGrid().getView().getWidget(i, be.getColIndex()))
                                            .setWidth(be.getWidth() - 10);
                                }
                            }
                        }
                    });
                }

                collectButton = new IconButton("starButton", new SelectionListener<IconButtonEvent>() {

                    @Override
                    public void componentSelected(IconButtonEvent ce) {

                        if (Controller.getIntsance().isDemoMode()) {
                            Controller.getIntsance().showSignupDialog();

                        } else {
                            if (model.getStarCount() == null || model.getStarCount().equals(0)) {
                                Controller.getEventBus().fireEvent(new RecordEventEvent(EventType.STARRED,
                                        model.getSongId(), Controller.getIntsance().getUserId()));
                                model.setStarCount(1);
                                ce.getIconButton().changeStyle("starButton-pressed");
                                MP3PlayerInfo.display("Info",
                                        "You collected " + model.getSongName() + " by " + model.getArtist());

                            } else {
                                Controller.getEventBus().fireEvent(new RecordEventEvent(EventType.UNSTARRED,
                                        model.getSongId(), Controller.getIntsance().getUserId()));
                                model.setStarCount(0);
                                ce.getIconButton().changeStyle("starButton");
                                MP3PlayerInfo.display("Info",
                                        "You un-collected " + model.getSongName() + " by + " + model.getArtist());

                            }
                        }
                    }
                });

                if (model.getStarCount() != null && model.getStarCount() > 0) {
                    collectButton.changeStyle("starButton-pressed");
                }

                // toggleButton.setHeight(20);
                collectButton.setWidth(grid.getColumnModel().getColumnWidth(colIndex) - 10);
                collectButton.setContextMenu(createCollectiveContextMenu(model));
                collectButton.setToolTip("Right click me");
                return collectButton;

            }
        };

        GridCellRenderer<SongModelData> buyButtonRenderer = new GridCellRenderer<SongModelData>() {

            public Object render(final SongModelData model, String property, ColumnData config, final int rowIndex,
                    final int colIndex, ListStore<SongModelData> store, Grid<SongModelData> grid) {

                buyButton = new IconButton("buyButton", new SelectionListener<IconButtonEvent>() {

                    @Override
                    public void componentSelected(IconButtonEvent ce) {
                        // TODO Auto-generated method stub

                    }
                });

                return buyButton;
            }

        };

        List<ColumnConfig> columns = new ArrayList<ColumnConfig>();
        ColumnConfig column = new ColumnConfig("songName", "Song Name", 200);
        columns.add(column);
        columns.add(new ColumnConfig("artist", "Artist", 150));
        columns.add(new ColumnConfig("album", "Album", 125));
        column = new ColumnConfig("sizeInBytes", "Size", 100);
        column.setHidden(true);
        columns.add(column);
        columns.add(new ColumnConfig("genre", "Genre", 100));
        starCountcolumn = new ColumnConfig("starCount", "Like", 30);
        starCountcolumn.setRenderer(voteUpButtonRenderer);
        starCountcolumn.setAlignment(HorizontalAlignment.LEFT);
        // Add a right click!?
        // tarCountcolumn.)
        columns.add(starCountcolumn);

        // totalStarCountColumn = new ColumnConfig("totalStarCount",
        // "Collected", 40);
        // column.setRenderer(totalSongCount);
        // column.setAlignment(HorizontalAlignment.CENTER);
        // columns.add(totalStarCountColumn);

        column = new ColumnConfig("alias", "Uploaded By", 100);
        columns.add(column);

        column = new ColumnConfig("playCount", "Play Count", 65);
        column.setAlignment(HorizontalAlignment.CENTER);
        columns.add(column);

        column = new ColumnConfig("createDate", "Date Uploaded", 85);
        column.setAlignment(HorizontalAlignment.CENTER);
        column.setHidden(true);
        columns.add(column);

        column = new ColumnConfig("buy", "Buy", 30);
        column.setRenderer(buyButtonRenderer);
        column.setHidden(true);
        column.setAlignment(HorizontalAlignment.CENTER);
        columns.add(column);

        columnModel = new ColumnModel(columns);

        proxy = new RpcProxy<PagingLoadResult<SongModelData>>() {
            @Override
            public void load(Object loadConfig, AsyncCallback<PagingLoadResult<SongModelData>> callback) {
                SiteServiceImpl.getInstance().getSongs((PagingLoadConfig) loadConfig,
                        Controller.getIntsance().getPlaylistUserId(), collectiveUserId,
                        Controller.getIntsance().getSearchTerm(), Controller.getIntsance().getPlaylistId(),
                        Controller.getIntsance().getSongRetrievalType(), callback);

            }
        };

        // loader
        loader = new BasePagingLoader<PagingLoadResult<SongModelData>>(proxy);

        loader.setRemoteSort(true);

        store = new GroupingStore<SongModelData>(loader);

        pagingToolBar.bind(loader);

        final ColumnModel columnModel = getColulmnModel();
        grid = new Grid<SongModelData>(store, columnModel);

        grid.setStateId("playlistGrid");
        grid.setStateful(true);
        grid.setAutoExpandColumn("songName");
        grid.setLoadMask(true);
        grid.setBorders(true);
        grid.setStripeRows(true);
        grid.clearState();

        grid.addListener(Events.RowDoubleClick, new Listener<GridEvent<SongModelData>>() {

            public void handleEvent(GridEvent<SongModelData> be) {

                SongModelData data = be.getModel();
                populatePlaylist(be.getRowIndex());
                Controller.getEventBus().fireEvent(new PlaySongEvent(data, Controller.getIntsance().getVolume()));

                pagingToolBar.enable();

            }

        });

        grid.addListener(Events.Attach, new Listener<GridEvent<SongModelData>>() {
            public void handleEvent(GridEvent<SongModelData> be) {
                Controller.getIntsance().getMainPage().showPlayListInCenter();
                pagingLoadConfig = new BasePagingLoadConfig();
                pagingLoadConfig.setOffset(0);
                pagingLoadConfig.setLimit(PAGING_SIZE);

                Map<String, Object> state = grid.getState();
                if (state.containsKey("offset")) {
                    int offset = (Integer) state.get("offset");
                    int limit = (Integer) state.get("limit");
                    pagingLoadConfig.setOffset(offset);
                    pagingLoadConfig.setLimit(limit);
                }
                if (state.containsKey("sortField")) {
                    pagingLoadConfig.setSortField((String) state.get("sortField"));
                    pagingLoadConfig.setSortDir(SortDir.valueOf((String) state.get("sortDir")));
                }
                if (Window.Location.getHash() == null || Window.Location.getHash().length() <= 0) {
                    loader.load(pagingLoadConfig);
                }

            }
        });

        loader.addLoadListener(new LoadListener() {
            @SuppressWarnings("unchecked")
            @Override
            public void loaderLoad(final com.extjs.gxt.ui.client.data.LoadEvent le) {
                pagingToolBar.enable();
                Controller.getIntsance().setLoadingState(LoadingState.FINISHED_LOADING);
                DeferredCommand.addCommand(new Command() {

                    @Override
                    public void execute() {

                        if (le.getData() instanceof BasePagingLoadResult) {
                            BasePagingLoadResult result = le.getData();

                            Log.debug("LoadingState = " + Controller.getIntsance().getLoadingState()
                                    + " SongRetrivalType = " + Controller.getIntsance().getSongRetrievalType()
                                    + "Total Length = " + result.getTotalLength());

                            if (result.getOffset() > result.getTotalLength()) {
                                pagingLoadConfig.setOffset(0);

                                loader.load(pagingLoadConfig);

                            }

                        }

                    }
                });

                if (Controller.getIntsance().getSongRetrievalType().equals(SongRetrievalType.PLAYLIST)) {
                    populatePlaylist(-1);
                    Controller.getEventBus()
                            .fireEvent(new PlaySongEvent(Controller.getPlaylistManager().getCurrentSong(),
                                    Controller.getIntsance().getVolume()));
                }
                //            else if (Controller.getIntsance().getSongRetrievalType().equals(SongRetrievalType.COLLECTIVE)) {
                //               populatePlaylist(-1);
                //               Controller.getEventBus().fireEvent(new PlaySongEvent(Controller.getPlaylistManager().getCurrentSong(), Controller.getIntsance().getVolume()));
                //            }
                else if (Controller.getIntsance().getSongRetrievalType()
                        .equals(SongRetrievalType.SIMILAR_ARTIST_SEARCH_RANDOM)) {
                    populatePlaylist(-1);
                }

            }

            private int getColumnIndex(List<ColumnConfig> columnsToSearch, String id) {
                int i = 0;
                for (ColumnConfig columnConfig : columnsToSearch) {
                    if (columnConfig.getId().equals(id))
                        return i;
                    else
                        i++;
                }
                return 0;
            }
        });

        dragSource = new GridDragSource(grid) {
            @Override
            protected void onDragDrop(final DNDEvent e) {

                if (DragDropUtility.isTargetSonglistPanel(e)) {
                    super.onDragDrop(e);

                } else {

                }

            }

        };
        target = new GridDropTarget(grid) {
            @SuppressWarnings("unchecked")
            @Override
            protected void onDragDrop(DNDEvent e) {

                if (DragDropUtility.isSourcePlaylistMenuComponent(e)) {

                    List modelDatalist = (List) e.getData();
                    if (modelDatalist != null) {
                        TreeStoreModel modelData = (TreeStoreModel) modelDatalist.get(0);
                        PlaylistModelData model = modelData.get("model");
                        if (model != null) {
                            Controller.getEventBus().fireEvent(new EditPlaylistEvent(model));
                        } else {
                            // For songs
                            // grid.getStore().add(model);
                            // populatePlaylist(Controller.getPlaylistManager().getPlaylistIndex());
                        }
                    }

                } else {

                    if (Controller.getIntsance().isPlaylistEditMode()) {

                        List modelDatalist = (List) e.getData();
                        if (modelDatalist != null) {

                            super.onDragDrop(e);
                            DeferredCommand.addCommand(new Command() {

                                @Override
                                public void execute() {
                                    Controller.getEventBus().fireEvent(new RemoveAllSongsFromPlaylistEvent(
                                            Controller.getIntsance().getPlaylistId()));

                                }

                            });
                            DeferredCommand.addCommand(new Command() {

                                @Override
                                public void execute() {
                                    List songs = grid.getStore().getModels();
                                    Controller.getEventBus().fireEvent(new AddSongToPlaylistEvent(
                                            Controller.getIntsance().getPlaylist(), songs));

                                }
                            });

                            // Controller.getEventBuss().fireEvent(new
                            // RemoveAllSongsFromPlaylistEvent(playlistId));
                            //
                            // final PlaylistModelData parent =
                            // getParentForChild(child);
                            //
                            // DeferredCommand.addCommand(new Command() {
                            //
                            // @Override
                            // public void execute() {
                            //
                            // Controller.getEventBuss().fireEvent(
                            // new AddSongToPlaylistEvent(parent,
                            // convertPlaylistModelDataToSongModelDataForAddingSongsToPlaylists(getChildrenForParent(parent))));
                            // }
                            // });
                            //
                            // }
                        }
                    } else {
                        super.onDragDrop(e);
                        populatePlaylist(Controller.getPlaylistManager().getPlaylistIndex());
                    }
                }
            }

        };

        GroupingView view = new GroupingView();
        view.setShowGroupedColumn(false);
        view.setForceFit(true);
        view.setGroupRenderer(new GridGroupRenderer() {
            public String render(GroupColumnData data) {
                String f = columnModel.getColumnById(data.field).getHeader();
                String l = data.models.size() == 1 ? "Item" : "Items";
                return f + ": " + data.group + " (" + data.models.size() + " " + l + ")";
            }
        });

        grid.setView(view);

        target.setAllowSelfAsSource(true);
        target.setFeedback(Feedback.INSERT);

        contentPanel = new ContentPanel();
        contentPanel.setFrame(true);
        contentPanel.setCollapsible(false);
        contentPanel.setAnimCollapse(false);

        contentPanel.setHeading("Playlist - The Collective");
        contentPanel.setLayout(new FitLayout());
        contentPanel.add(grid);

        contentPanel.setTopComponent(searchComponent);
        contentPanel.setBottomComponent(pagingToolBar);

        searchComponent.setToolTip("Search artists, albums, and genres");
        pagingToolBar.setToolTip("Pagination Options");
        // grid.setToolTip("Right click me for more options.");

        setLayout(new FitLayout());
        add(contentPanel);

    }

    protected Menu createCollectiveContextMenu(final SongModelData model) {

        Menu menu = new Menu();

        String title = model.getTotalStarCount().toString();

        title += model.getTotalStarCount() == 1 ? " user " : " users ";

        title += "collected this song";
        MenuItem item = new MenuItem(title, new SelectionListener<MenuEvent>() {

            @Override
            public void componentSelected(MenuEvent ce) {

                showUsersWhoCollectedSongDialog.setSongId(model.getSongId());
                showUsersWhoCollectedSongDialog.showAndLoad();

            }
        });
        menu.add(item);

        return menu;

    }

    private void setTitleForContentPanel(String title) {
        contentPanel.setHeading(title);
    }

    private ColumnModel getColulmnModel() {
        return columnModel;
    }

    protected void populatePlaylist(Integer rowIndexStart) {
        populatePlaylist(rowIndexStart, true);
    }

    protected void populatePlaylist(Integer rowIndexStart, Boolean resetShuffle) {

        if (previousSongs.size() != grid.getStore().getModels().size()) {
            Controller.getIntsance().resetShuffleAndRepeat();
        }

        Controller.getPlaylistManager().resetPlaylist();
        List<SongModelData> playlist = Controller.getPlaylistManager().getPlaylist();

        playlist.addAll(grid.getStore().getModels());
        Controller.getPlaylistManager().setPlaylist(playlist, rowIndexStart);

    }

    public void addEventHandlers() {
        Controller.getEventBus().addHandler(GetRecentlyUploadedSongsFromUserAndAllFriendsEvent.TYPE,
                new GetRecentlyUploadedSongsFromUserAndAllFriendsEventHandler() {

                    @Override
                    public void handle(Long userId) {
                        setTitleForContentPanel("Playlist - Recently Uploaded");
                        Controller.getIntsance().setSongRetrievalType(SongRetrievalType.RECENLTY_UPLOADED);
                        loader.load();
                    }
                });
        Controller.getEventBus().addHandler(GetRecentlyUploadedSongsFromAllEvent.TYPE,
                new GetRecentlyUploadedSongsFromAllEventHandler() {

                    @Override
                    public void handle(Long userId) {

                        Controller.getIntsance().setSongRetrievalType(SongRetrievalType.RECENLTY_UPLOADED_ALL);
                        loader.load();
                    }
                });

        Controller.getEventBus().addHandler(ShowNowPlayingEvent.TYPE, new ShowNowPlayingEventHandler() {

            @Override
            public void handle() {
                setTitleForContentPanel("Playlist - Now Playing");

                grid.getStore().removeAll();
                grid.getStore().add(Controller.getPlaylistManager().getPlaylist());

            }
        });

        Controller.getEventBus().addHandler(SongFinishedLoadingEvent.TYPE, new SongFinishedLoadingEventHandler() {

            @Override
            public void handle(SongModelData song) {

            }
        });

        Controller.getEventBus().addHandler(PlaySongEvent.TYPE, new PlaySongEventHandler() {

            @Override
            public void handle(SongModelData song, Integer volume) {
                RequestBuilder builder = new RequestBuilder(RequestBuilder.GET,
                        GWT.getHostPageBaseURL() + "servlet/albumArtwork?artist=" + URL.encode(song.getArtist())
                                + "&album=" + URL.encode(song.getAlbum()));
                try {
                    selectSongOnGrid(song);
                    Window.setTitle(song.getArtist() + " - " + song.getSongName());

                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }

        });

        Controller.getEventBus().addHandler(GetCollectiveSongsForUserEvent.TYPE,
                new GetCollectiveSongsForUserEventHandler() {

                    @Override
                    public void handle(Long userId) {
                        setTitleForContentPanel("Playlist - Collective Songs For User");
                        Controller.getIntsance().setSongRetrievalType(SongRetrievalType.USER_COLLECTIVE);
                        collectiveUserId = userId;
                        loader.load();

                    }
                });

        Controller.getEventBus().addHandler(RandomizePlaylistEvent.TYPE, new RandomizePlaylistEventHandler() {

            @Override
            public void handle() {
                grid.mask("Shuffling...");
                randomizePlaylist();
                grid.unmask();

            }
        });

        Controller.getEventBus().addHandler(UnrandomizePlaylistEvent.TYPE, new UnrandomizePlaylistEventHandler() {

            @Override
            public void handle() {
                unrandomizePlaylist();

            }
        });

        Controller.getEventBus().addHandler(PlaylistsNeedReloadingEvent.TYPE,
                new PlaylistsNeedReloadingEventHandler() {

                    @Override
                    public void handle() {

                        PlaylistModelData model = new PlaylistModelData();
                        model.setUserId(Controller.getIntsance().getUserId());
                        SiteServiceImpl.getInstance().getPlaylists(model, Controller.getIntsance().getUserId(),
                                new AsyncCallback<List<PlaylistModelData>>() {

                                    @Override
                                    public void onSuccess(List<PlaylistModelData> result) {
                                        Controller.getEventBus().fireEvent(new PlaylistsListLoadedEvent(result));

                                    }

                                    @Override
                                    public void onFailure(Throwable caught) {

                                    }
                                });

                    }
                });

        Controller.getEventBus().addHandler(GetSongsForUserAndAllFriendsEvent.TYPE,
                new GetSongsForUserAndAllFriendsEventHandler() {

                    @Override
                    public void handle(Long userId) {
                        Controller.getIntsance().setSongRetrievalType(SongRetrievalType.ALL_USERS);
                        loader.load();

                    }
                });

        Controller.getEventBus().addHandler(GetSongsForAllEvent.TYPE, new GetSongsForAllEventHandler() {

            @Override
            public void handle(Long userId) {
                setTitleForContentPanel("Playlist - All Music");
                Controller.getIntsance().setSongRetrievalType(SongRetrievalType.ALL_USERS);
                loader.load();

            }
        });

        Controller.getEventBus().addHandler(GetCollectiveSongsForUserAndAllFriendsEvent.TYPE,
                new GetCollectiveSongsForUserAndAllFriendsEventHandler() {

                    @Override
                    public void handle(Long userId) {
                        // setTitleForContentPanel("Playlist - The Collective");
                        // starCountcolumn.setHeader("# Users");
                        setTitleForContentPanel("Playlist - The Collective");
                        Controller.getIntsance().setSongRetrievalType(SongRetrievalType.COLLECTIVE);
                        loader.load();

                    }
                });

        Controller.getEventBus().addHandler(PlaylistsListLoadedEvent.TYPE, new PlaylistsListLoadedEventHandler() {

            @Override
            public void handle(List<PlaylistModelData> playlists) {

                playlistSubMenu.removeAll();
                playlistSubMenu.add(newPlaylist);
                playlistSubMenu.add(new SeparatorMenuItem());

                for (final PlaylistModelData playlistModelData : playlists) {
                    playlistSubMenu
                            .add(new MenuItem(playlistModelData.getName(), new SelectionListener<MenuEvent>() {

                                @Override
                                public void componentSelected(MenuEvent ce) {

                                    Controller.getEventBus().fireEvent(
                                            new AddSongToPlaylistEvent(playlistModelData, getSelectedSongs()));
                                }

                            }));
                }

                playlistTopLevelMenu.setSubMenu(playlistSubMenu);
            }
        });

        Controller.getEventBus().addHandler(PlayPlaylistEvent.TYPE, new PlayPlaylistEventHandler() {

            @Override
            public void handle(PlaylistModelData playlist) {
                setTitleForContentPanel("Playlist - Playing playlist [" + playlist.getName() + "]");

                Controller.getIntsance().setPlaylist(playlist);
                Controller.getIntsance().setSongRetrievalType(SongRetrievalType.PLAYLIST);

                loader.load();

            }
        });

        Controller.getEventBus().addHandler(EditPlaylistEvent.TYPE, new EditPlaylistEventHandler() {

            @Override
            public void handle(PlaylistModelData playlist) {
                setTitleForContentPanel("Playlist - Editing playlist [" + playlist.getName() + "]");

                Controller.getIntsance().setPlaylist(playlist);
                Controller.getIntsance().setSongRetrievalType(SongRetrievalType.EDIT_PLAYLIST);

                loader.load();

            }
        });

        Controller.getEventBus().addHandler(GetSongsForUserEvent.TYPE, new GetSongsForUserEventHandler() {

            @Override
            public void handle(Long userId) {
                setTitleForContentPanel("Playlist - All Songs For User");
                Controller.getIntsance().getMainPage().showPlayListInCenter();
                Controller.getIntsance().setPlaylistUserId(userId);
                Controller.getIntsance().setSongRetrievalType(SongRetrievalType.SINGLE_USER);
                loader.load();

                // DeferredCommand.addCommand(new Command() {
                //
                // @Override
                // public void execute() {
                //
                // pagingToolBar.enable();
                // }
                //
                // });

            }
        });

        Controller.getEventBus().addHandler(SearchSongsFromAllFriendsPagedEvent.TYPE,
                new SearchSongsFromAllFriendsPagedEventHandler() {

                    @Override
                    public void handle(Long userId, String searchTerm) {
                        setTitleForContentPanel("Playlist - Song search [" + searchTerm + "]");
                        MP3PlayerInfo.display("Info", "Now searching for " + searchTerm);
                        Controller.getIntsance().setSearchTerm(searchTerm);
                        Controller.getIntsance().setSongRetrievalType(SongRetrievalType.SEARCH);
                        loader.load();
                        DeferredCommand.addCommand(new Command() {

                            @Override
                            public void execute() {
                                pagingToolBar.first();

                            }
                        });
                    }

                });

        Controller.getEventBus().addHandler(SearchSongsByArtistFromAllFriendsPagedEvent.TYPE,
                new SearchSongsByArtistFromAllFriendsPagedEventHandler() {

                    @Override
                    public void handle(Long userId, String searchTerm) {
                        MP3PlayerInfo.display("Info", "Now searching for the artist " + searchTerm);
                        setTitleForContentPanel("Playlist - Song search by artist [" + searchTerm + "]");
                        Controller.getIntsance().setSearchTerm(searchTerm);
                        Controller.getIntsance().setSongRetrievalType(SongRetrievalType.ARIST_SEARCH);
                        loader.load();
                        DeferredCommand.addCommand(new Command() {

                            @Override
                            public void execute() {
                                pagingToolBar.first();

                            }
                        });
                    }

                });

        Controller.getEventBus().addHandler(SearchSongsByAlbumFromAllFriendsPagedEvent.TYPE,
                new SearchSongsByAlbumFromAllFriendsPagedEventHandler() {

                    @Override
                    public void handle(Long userId, String searchTerm) {
                        setTitleForContentPanel("Playlist - Song search by album [" + searchTerm + "]");
                        MP3PlayerInfo.display("Info", "Now searching for the album " + searchTerm);
                        Controller.getIntsance().setSearchTerm(searchTerm);
                        Controller.getIntsance().setSongRetrievalType(SongRetrievalType.ALBUM_SEARCH);
                        loader.load();
                        DeferredCommand.addCommand(new Command() {

                            @Override
                            public void execute() {
                                pagingToolBar.first();

                            }
                        });
                    }

                });

        Controller.getEventBus().addHandler(SearchSongsByGenreFromAllFriendsPagedEvent.TYPE,
                new SearchSongsByGenreFromAllFriendsPagedEventHandler() {

                    @Override
                    public void handle(Long userId, String searchTerm) {
                        MP3PlayerInfo.display("Info", "Now searching for the genre " + searchTerm);
                        setTitleForContentPanel("Playlist - Song search by album [" + searchTerm + "]");
                        Controller.getIntsance().setSearchTerm(searchTerm);
                        Controller.getIntsance().setSongRetrievalType(SongRetrievalType.GENRE_SEARCH);
                        loader.load();
                        DeferredCommand.addCommand(new Command() {

                            @Override
                            public void execute() {
                                pagingToolBar.first();

                            }
                        });
                    }

                });

        Controller.getEventBus().addHandler(SearchSongsByThisAndSimilarArtistsFromAllFriendsPagedEvent.TYPE,
                new SearchSongsByThisAndSimilarArtistsFromAllFriendsPagedEventHandler() {

                    @Override
                    public void handle(Long userId, String searchTerm) {
                        MP3PlayerInfo.display("Info", "Now searching for " + searchTerm + " and similar artists.");
                        Controller.getIntsance().setSearchTerm(searchTerm);
                        Controller.getIntsance().setSongRetrievalType(SongRetrievalType.SIMILAR_ARTIST_SEARCH);
                        loader.load();
                        DeferredCommand.addCommand(new Command() {

                            @Override
                            public void execute() {
                                pagingToolBar.first();

                            }
                        });
                    }

                });

        Controller.getEventBus().addHandler(SearchSongsRandomByThisAndSimilarArtistsFromAllFriendsPagedEvent.TYPE,
                new SearchSongsRandomByThisAndSimilarArtistsFromAllFriendsPagedEventHandler() {

                    @Override
                    public void handle(Long userId, String searchTerm) {
                        MP3PlayerInfo.display("Info",
                                "Creating a playlist for similar artists of  " + searchTerm + "");
                        Controller.getIntsance().setSearchTerm(searchTerm);
                        Controller.getIntsance()
                                .setSongRetrievalType(SongRetrievalType.SIMILAR_ARTIST_SEARCH_RANDOM);
                        loader.load();
                        DeferredCommand.addCommand(new Command() {

                            @Override
                            public void execute() {

                                Controller.getPlaylistManager().resetPlaylist();
                                List<SongModelData> playlist = Controller.getPlaylistManager().getPlaylist();

                                Controller.getPlaylistManager().setPlaylist(playlist, 0);

                            }
                        });
                    }

                });

        // Legacy shit, this calls arent used anymore
        // Controller.getEventBuss().addHandler(SearchSongsForUserEvent.TYPE,
        // new SearchSongsForUserEventHandler(){
        //
        // @Override
        // public void handle(ArrayList<SongModelData> songs) {
        //            
        // songsByUserIdStore.removeAll();
        // songsByUserIdStore.add(songs);
        // grid.unmask();
        // Controller.getIntsance().ensurePlaylistIsVisible();
        // }
        //         
        // });
        //      
        // Controller.getEventBuss().addHandler(SearchSongsFromAllFriendsEvent.TYPE,
        // new SearchSongsFromAllFriendsEventHandler(){
        //
        // @Override
        // public void handle(ArrayList<SongModelData> songs) {
        //            
        // songsByUserIdStore.removeAll();
        // songsByUserIdStore.add(songs);
        // grid.unmask();
        // Controller.getIntsance().ensurePlaylistIsVisible();
        // }
        //         
        // });

    }

    public void selectSongOnGrid(SongModelData song) {
        ListStore<SongModelData> localStore = grid.getStore();
        int itemCount = 0;
        for (SongModelData song2 : localStore.getModels()) {
            if (song2.equals(song)) {
                break;
            } else
                itemCount++;
        }
        grid.getSelectionModel().select(song, false);
        grid.getView().focusRow(itemCount);

    }

    protected void unrandomizePlaylist() {
        grid.getStore().removeAll();
        grid.getStore().add(previousSongs);
        populatePlaylist(0, false);

    }

    protected void randomizePlaylist() {

        previousSongs.clear();
        previousSongs.addAll(grid.getStore().getModels());

        SongModelData[] randomizedSongs = previousSongs.toArray(new SongModelData[] {});

        // --- Shuffle by exchanging each element randomly
        for (int i = 0; i < randomizedSongs.length; i++) {
            int randomPosition = Random.nextInt(randomizedSongs.length);
            SongModelData temp = randomizedSongs[i];
            randomizedSongs[i] = randomizedSongs[randomPosition];
            randomizedSongs[randomPosition] = temp;
        }

        grid.getStore().removeAll();
        grid.getStore().add(Arrays.asList(randomizedSongs));
        populatePlaylist(-1, false);

    }

    public Grid<SongModelData> getPlaylistGrid() {
        return grid;
    }

    public ContentPanel getContentPanel() {
        return contentPanel;
    }

    public void setContentPanel(ContentPanel contentPanel) {
        this.contentPanel = contentPanel;
    }

    private Menu createContextMenu() {
        Menu menu = new Menu();

        // MenuItem addUser = new MenuItem("Add Song", new
        // SelectionListener<MenuEvent>() {
        //
        // @Override
        // public void componentSelected(MenuEvent ce) {
        // Controller.getEventBuss().fireEvent(new
        // UploadYourMusicEvent());
        //
        // }
        //
        // });
        // addUser.setIcon(Controller.getIntsance().getIcons().addSong());
        // menu.add(addUser);

        MenuItem removeTopLevelMenu = new MenuItem("Remove");
        Menu removeSubMenu = new Menu();

        MenuItem removeUser = new MenuItem("Remove Song from view", new SelectionListener<MenuEvent>() {

            @Override
            public void componentSelected(MenuEvent ce) {

                List<SongModelData> songs = getSelectedSongs();
                if (songs != null) {
                    if (Controller.getIntsance().isPlaylistEditMode()) {
                        Controller.getEventBus().fireEvent(
                                new RemoveSongFromPlaylistEvent(Controller.getIntsance().getPlaylist(), songs));

                        for (SongModelData songModelData : songs) {

                            grid.getStore().remove(songModelData);

                        }
                        Controller.getPlaylistManager().removeSongsFromPlaylist(songs);

                    } else {
                        MP3PlayerInfo.display("Info", "Removing " + songs.size() + " songs from this view.");
                        for (SongModelData songModelData : songs) {

                            grid.getStore().remove(songModelData);

                        }

                        Controller.getPlaylistManager().removeSongsFromPlaylist(songs);
                    }

                }

            }

        });

        MenuItem removeArtist = new MenuItem("Remove Artist from view", new SelectionListener<MenuEvent>() {

            @Override
            public void componentSelected(MenuEvent ce) {

                List<SongModelData> songs = new ArrayList<SongModelData>();
                List<SongModelData> selectedSongs = getSelectedSongs();

                for (SongModelData songModelData : selectedSongs) {

                    songs.addAll(getSongsByArtist(songModelData));
                }

                if (songs != null) {
                    if (Controller.getIntsance().isPlaylistEditMode()) {
                        Controller.getEventBus().fireEvent(
                                new RemoveSongFromPlaylistEvent(Controller.getIntsance().getPlaylist(), songs));

                        for (SongModelData songModelData : songs) {

                            grid.getStore().remove(songModelData);

                        }

                        Controller.getPlaylistManager().removeSongsFromPlaylist(songs);

                    } else {
                        MP3PlayerInfo.display("Info", "Removing " + songs.size() + " songs from this view.");
                        for (SongModelData songModelData : songs) {

                            grid.getStore().remove(songModelData);

                        }
                        Controller.getPlaylistManager().removeSongsFromPlaylist(songs);
                    }

                }

            }

        });

        removeTopLevelMenu.setIcon(Controller.getIntsance().getIcons().deleteSong());
        removeTopLevelMenu.setSubMenu(removeSubMenu);
        removeSubMenu.add(removeUser);
        removeSubMenu.add(removeArtist);

        // menu.add(new SeparatorMenuItem());
        // MenuItem recommendThisTopLevelMenu = new MenuItem("Recommend this");
        // Menu recommendThisSubMenu = new Menu();
        //
        // MenuItem recomendThisToAFriend = new
        // MenuItem("Recommend this to a friend", new
        // SelectionListener<MenuEvent>() {
        //
        // @Override
        // public void componentSelected(MenuEvent ce) {
        // selectUserDialog.setRecommendationModelData(getRecommendationModelDataFromCurrentSelection());
        // selectUserDialog.show();
        //
        // }
        //
        // });
        // MenuItem recommendThisToAllFriends = new
        // MenuItem("Recommend this to all friends",
        // new SelectionListener<MenuEvent>() {
        //
        // @Override
        // public void componentSelected(MenuEvent ce) {
        // Controller.getEventBuss().fireEvent(
        // new
        // AddRecommendationEvent(getRecommendationModelDataFromCurrentSelection()));
        //
        // }
        //
        // });
        //
        // recomendThisToAFriend.setIcon(Controller.getIntsance().getIcons().recommendation());
        // recommendThisToAllFriends.setIcon(Controller.getIntsance().getIcons().recommendations());
        //
        // recommendThisSubMenu.add(recomendThisToAFriend);
        // recommendThisSubMenu.add(recommendThisToAllFriends);
        //
        // recommendThisTopLevelMenu.setIcon(Controller.getIntsance().getIcons().recommendations());
        //
        // recommendThisTopLevelMenu.setSubMenu(recommendThisSubMenu);
        //
        // menu.add(recommendThisTopLevelMenu);

        MenuItem nowPlaylingTopLevelMenu = new MenuItem("Add to now playing");
        nowPlaylingTopLevelMenu.setIcon(Controller.getIntsance().getIcons().bulletImage());
        Menu nowPlayingSubMenu = new Menu();
        nowPlaylingTopLevelMenu.setSubMenu(nowPlayingSubMenu);

        MenuItem nowPlayingAddToEnd = new MenuItem("Add To End", new SelectionListener<MenuEvent>() {

            @Override
            public void componentSelected(MenuEvent ce) {

                Controller.getPlaylistManager().addSongsToPlaylist(getSelectedSongs());

            }
        });

        MenuItem nowPlayingAddAfterCurrent = new MenuItem("Add After Current", new SelectionListener<MenuEvent>() {

            @Override
            public void componentSelected(MenuEvent ce) {
                Controller.getPlaylistManager().addSongsToPlaylistAfterCurrentSong(getSelectedSongs());

            }
        });

        nowPlayingSubMenu.add(nowPlayingAddToEnd);
        nowPlayingSubMenu.add(nowPlayingAddAfterCurrent);

        playlistTopLevelMenu = new MenuItem("Add to playlist");
        playlistSubMenu = new Menu();
        playlistTopLevelMenu.setSubMenu(playlistSubMenu);

        newPlaylist = new MenuItem("New Playlist", new SelectionListener<MenuEvent>() {

            @Override
            public void componentSelected(MenuEvent ce) {
                if (Controller.getIntsance().isDemoMode()) {
                    Controller.getIntsance().showSignupDialog();

                } else {
                    final Listener<MessageBoxEvent> onOk = new Listener<MessageBoxEvent>() {
                        public void handleEvent(MessageBoxEvent ce) {
                            if (ce.getButtonClicked().getText().equals("Ok")) {
                                Controller.getEventBus()
                                        .fireEvent(new AddPlaylistEvent(ce.getValue(), new AsyncCallback<Long>() {

                                            @Override
                                            public void onSuccess(Long result) {

                                                Controller.getEventBus().fireEvent(
                                                        new AddSongToPlaylistEvent(result, getSelectedSongs()));
                                                DeferredCommand.addCommand(new Command() {

                                                    @Override
                                                    public void execute() {
                                                        Controller.getEventBus()
                                                                .fireEvent(new PlaylistsNeedReloadingEvent());

                                                    }
                                                });
                                            }

                                            @Override
                                            public void onFailure(Throwable caught) {
                                                Window.alert("FAILED");

                                            }
                                        }));

                            }
                        }
                    };

                    MessageBox box = new MessageBox();
                    box.setButtons(MessageBox.OKCANCEL);
                    box.setIcon(MessageBox.QUESTION);
                    box.setType(MessageBox.MessageBoxType.PROMPT);

                    box.setTitle("Playlist Name?");
                    box.setMinWidth(300);
                    box.addCallback(onOk);
                    box.show();
                }

            }

        });

        playlistTopLevelMenu.setIcon(Controller.getIntsance().getIcons().musicNoteImage());

        // MenuItem createPlaylistTopLevelMenu = new
        // MenuItem("Create playlist");
        // createPlaylistTopLevelMenu.setIcon(Controller.getIntsance().getIcons().searchSongs());
        //
        // Menu createPlaylistSubMenu = new Menu();
        //      
        // MenuItem createPlaylistOfThisArtist = new MenuItem("Of This Artist",
        // new SelectionListener<MenuEvent>() {
        //
        // @Override
        // public void componentSelected(MenuEvent ce) {
        //
        // Controller.getEventBuss().fireEvent(
        // new CreatePlaylistOfThisArtistEvent(getSelectedSong()));
        //
        // }
        //
        // });
        //      
        // MenuItem createPlaylistOfThisAndSimilarArtist = new
        // MenuItem("Of This And Similar Artist", new
        // SelectionListener<MenuEvent>() {
        //
        // @Override
        // public void componentSelected(MenuEvent ce) {
        //
        // Controller.getEventBuss().fireEvent(
        // new CreatePlaylistOfThisAndSimilarArtistsEvent(getSelectedSong()));
        //
        // }
        //
        // });
        //      
        //      
        //      
        // createPlaylistSubMenu.add(createPlaylistOfThisArtist);
        // createPlaylistSubMenu.add(createPlaylistOfThisAndSimilarArtist);
        //      
        //      
        // createPlaylistTopLevelMenu.setSubMenu(createPlaylistSubMenu);
        // menu.add(createPlaylistTopLevelMenu);

        // menu.add(new SeparatorMenuItem());

        MenuItem searchTopLevelMenu = new MenuItem("Search");
        searchTopLevelMenu.setIcon(Controller.getIntsance().getIcons().searchSongs());

        Menu searchSubMenu = new Menu();

        MenuItem searchArtist = new MenuItem("Search for this Artist", new SelectionListener<MenuEvent>() {

            @Override
            public void componentSelected(MenuEvent ce) {

                Controller.getEventBus().fireEvent(new SearchSongsByArtistFromAllFriendsPagedEvent(
                        Controller.getIntsance().getPlaylistUserId(), getSelectedSong().getArtist()));

            }

        });
        // searchArtist.setIcon(Controller.getIntsance().getIcons().searchSongs());

        MenuItem searchAlbulm = new MenuItem("Search for this Album", new SelectionListener<MenuEvent>() {

            @Override
            public void componentSelected(MenuEvent ce) {

                Controller.getEventBus().fireEvent(new SearchSongsByAlbumFromAllFriendsPagedEvent(
                        Controller.getIntsance().getPlaylistUserId(), getSelectedSong().getAlbum()));

            }

        });
        // searchAlbulm.setIcon(Controller.getIntsance().getIcons().searchSongs());

        MenuItem searchGenre = new MenuItem("Search for this Genre", new SelectionListener<MenuEvent>() {

            @Override
            public void componentSelected(MenuEvent ce) {

                Controller.getEventBus().fireEvent(new SearchSongsByGenreFromAllFriendsPagedEvent(
                        Controller.getIntsance().getPlaylistUserId(), getSelectedSong().getGenre()));

            }

        });
        // searchGenre.setIcon(Controller.getIntsance().getIcons().searchSongs());
        MenuItem searchSimilarArtists = new MenuItem("Search for this and Similar Artists",
                new SelectionListener<MenuEvent>() {

                    @Override
                    public void componentSelected(MenuEvent ce) {

                        Controller.getEventBus()
                                .fireEvent(new SearchSongsByThisAndSimilarArtistsFromAllFriendsPagedEvent(
                                        Controller.getIntsance().getPlaylistUserId(),
                                        getSelectedSong().getArtist()));

                    }

                });
        searchSubMenu.add(searchSimilarArtists);
        searchSubMenu.add(new SeparatorMenuItem());
        searchSubMenu.add(searchArtist);
        searchSubMenu.add(searchAlbulm);
        searchSubMenu.add(searchGenre);

        searchTopLevelMenu.setSubMenu(searchSubMenu);

        MenuItem infoTopLevelMenu = new MenuItem("Info");
        infoTopLevelMenu.setIcon(Controller.getIntsance().getIcons().similarArtist());

        Menu infoSubMenu = new Menu();

        MenuItem artistInfo = new MenuItem("View Artist Info", new SelectionListener<MenuEvent>() {

            @Override
            public void componentSelected(MenuEvent ce) {

                SongModelData song = getSelectedSong();
                if (song != null) {
                    Controller.getEventBus().fireEvent(new ArtistInfoEvent(song.getArtist()));

                }

            }

        });

        infoSubMenu.add(artistInfo);

        // infoSubMenu.add(similarArtists);

        MenuItem artistPhotos = new MenuItem("View Artist Photos", new SelectionListener<MenuEvent>() {

            @Override
            public void componentSelected(MenuEvent ce) {

                SongModelData song = getSelectedSong();
                if (song != null) {
                    Controller.getEventBus().fireEvent(new ArtistPhotosEvent(song.getArtist()));

                }

            }

        });

        infoSubMenu.add(artistPhotos);
        infoSubMenu.add(new SeparatorMenuItem());

        MenuItem editSongInfo = new MenuItem("Edit Song Info", new SelectionListener<MenuEvent>() {

            @Override
            public void componentSelected(MenuEvent ce) {

                SongModelData song = getSelectedSong();
                if (song != null) {

                    editSongInfoDialog.setSongModelData(song);
                    if (Controller.getIntsance().isDemoMode()) {
                        Controller.getIntsance().showSignupDialog();

                    } else if (song.getUserId().equals(Controller.getIntsance().getUserId())) {
                        editSongInfoDialog.show();
                    } else {
                        MessageBox.alert("I love you", "Sorry!  You need to be the owner of this song to edit it",
                                new Listener<MessageBoxEvent>() {

                                    @Override
                                    public void handleEvent(MessageBoxEvent be) {
                                        // TODO Auto-generated method stub

                                    }
                                });
                    }

                }

            }

        });

        infoSubMenu.add(editSongInfo);

        infoTopLevelMenu.setSubMenu(infoSubMenu);

        MenuItem showTopLevelMenu = new MenuItem("Show Music");
        showTopLevelMenu.setIcon(Controller.getIntsance().getIcons().bulletImage());

        Menu showSubMenu = new Menu();

        MenuItem showAllMusic = new MenuItem("All Music", new SelectionListener<MenuEvent>() {

            @Override
            public void componentSelected(MenuEvent ce) {
                Controller.getEventBus().fireEvent(new GetSongsForAllEvent(Controller.getIntsance().getUserId()));

            }

        });

        MenuItem nowPlaying = new MenuItem("Now Playing", new SelectionListener<MenuEvent>() {

            @Override
            public void componentSelected(MenuEvent ce) {
                Controller.getEventBus().fireEvent(new ShowNowPlayingEvent());

            }
        });

        MenuItem collectedMusic = new MenuItem("The Collective", new SelectionListener<MenuEvent>() {

            @Override
            public void componentSelected(MenuEvent ce) {
                Controller.getEventBus().fireEvent(
                        new GetCollectiveSongsForUserAndAllFriendsEvent(Controller.getIntsance().getUserId()));

            }
        });

        MenuItem recentlyUploaded = new MenuItem("Recently Uploaded", new SelectionListener<MenuEvent>() {

            @Override
            public void componentSelected(MenuEvent ce) {
                Controller.getEventBus()
                        .fireEvent(new GetRecentlyUploadedSongsFromAllEvent(Controller.getIntsance().getUserId()));

            }
        });

        showSubMenu.add(nowPlaying);
        showSubMenu.add(collectedMusic);
        showSubMenu.add(showAllMusic);
        showSubMenu.add(recentlyUploaded);

        showTopLevelMenu.setSubMenu(showSubMenu);

        MenuItem userTopLevelMenu = new MenuItem("Users");
        userTopLevelMenu.setIcon(Controller.getIntsance().getIcons().bulletImage());

        Menu userSubMenu = new Menu();

        MenuItem showMusicFromThisPerson = new MenuItem("Show This Users Music",
                new SelectionListener<MenuEvent>() {

                    @Override
                    public void componentSelected(MenuEvent ce) {
                        SongModelData selectedSong = getSelectedSong();

                        if (selectedSong != null) {

                            Controller.getEventBus().fireEvent(new GetSongsForUserEvent(selectedSong.getUserId()));
                        }

                    }
                });

        MenuItem showCollectiveFromThisPerson = new MenuItem("Show This Users Collective",
                new SelectionListener<MenuEvent>() {

                    @Override
                    public void componentSelected(MenuEvent ce) {
                        SongModelData song = getSelectedSong();
                        if (song != null && song.getUserId() != null) {
                            Controller.getEventBus()
                                    .fireEvent(new GetCollectiveSongsForUserEvent(song.getUserId()));
                        }

                    }
                });

        /*      MenuItem inviteFriend = new MenuItem("Invite This User as a Friend", new SelectionListener<MenuEvent>() {
            
                 @Override
                 public void componentSelected(MenuEvent ce) {
        if (getSelectedSong() != null) {
           Long userId = getSelectedSong().getUserId();
           if (!Controller.getIntsance().isFriendsWith(userId)) {
              Controller.getEventBus().fireEvent(new InviteFriendByUserIdEvent(userId));
           } else
              MP3PlayerInfo.display("Oops!", "Looks like you are already friends with this person!");
        }
            
                 }
              });
        */
        userSubMenu.add(showMusicFromThisPerson);
        userSubMenu.add(showCollectiveFromThisPerson);
        userSubMenu.add(new SeparatorMenuItem());
        //      userSubMenu.add(inviteFriend);

        userTopLevelMenu.setSubMenu(userSubMenu);
        userTopLevelMenu.setIcon(Controller.getIntsance().getIcons().getHappyFace());

        menu.add(showTopLevelMenu);
        menu.add(new SeparatorMenuItem());
        menu.add(searchTopLevelMenu);
        menu.add(new SeparatorMenuItem());
        menu.add(nowPlaylingTopLevelMenu);
        menu.add(new SeparatorMenuItem());
        menu.add(playlistTopLevelMenu);
        menu.add(new SeparatorMenuItem());
        menu.add(infoTopLevelMenu);
        menu.add(new SeparatorMenuItem());
        menu.add(userTopLevelMenu);
        menu.add(new SeparatorMenuItem());
        menu.add(removeTopLevelMenu);

        return menu;
    }

    protected Collection<? extends SongModelData> getSongsByArtist(SongModelData songModelData) {

        List<SongModelData> models = store.getModels();
        List<SongModelData> songs = new ArrayList<SongModelData>();
        for (SongModelData song : models) {
            if (song.getArtist().equals(songModelData.getArtist())) {
                songs.add(song);
            }

        }

        return songs;

    }

    public void showCurrentPlaylist() {

        Controller.getIntsance().setSongRetrievalType(SongRetrievalType.ALL_USERS);
        store.removeAll();
        store.add(Controller.getPlaylistManager().getPlaylist());
        grid.getSelectionModel().select(Controller.getSoundUtility().getCurrentSongModelData(), false);

    }

    private SongModelData getSelectedSong() {
        return grid.getSelectionModel().getSelectedItem();
    }

    private List<SongModelData> getSelectedSongs() {
        return grid.getSelectionModel().getSelectedItems();
    }

    public void reload() {
        loader.load();

    }

}