public class SongListAdapter extends SelectableAdapter<SongListAdapter.ViewHolder> {

    private List<SongDTO> songs;
    private final ContentType contentType;
    private ClickListener clickListener;

    public SongListAdapter(List<SongDTO> songs, ClickListener clickListener, ContentType contentType) {
        this.songs = songs;
        this.clickListener = clickListener;
        this.contentType = contentType;
    }

    @Override
    public SongListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        Context context = parent.getContext();
        LayoutInflater inflater = LayoutInflater.from(context);

        View contactView;

        if(contentType == ContentType.PLAYLIST){
            contactView = inflater.inflate(R.layout.remove_song_list_item, parent, false);
        } else {
            contactView = inflater.inflate(R.layout.add_song_list_item, parent, false);
        }

        return new ViewHolder(contactView, clickListener);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        holder.songTitle.setText(songs.get(position).getSongTitle());
        holder.songDuration.setText(TimeFormatUtils.secondsToTimer(songs.get(position).getSongDuration()));

        ObjectAnimator animX;
        if (isSelected(position)) {
            animX = ObjectAnimator.ofFloat(holder.rowView, "x", 150f);
        } else {
            animX = ObjectAnimator.ofFloat(holder.rowView, "x", 0f);
        }
        animX.setDuration(250);
        animX.start();
    }

    @Override
    public int getItemCount() {
        return songs.size();
    }

    public void updateSongs(List<SongDTO> songs){
        this.songs = songs;
        notifyDataSetChanged();
    }

    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {
        public TextView songTitle;
        public TextView songDuration;
        public View rowView;
        private ClickListener clickListener;

        public ViewHolder(View v, ClickListener clickListener) {
            super(v);
            songTitle = (TextView) v.findViewById(R.id.txt_song_item_title);
            songDuration = (TextView) v.findViewById(R.id.txt_song_item_duration);
            rowView = v.findViewById(R.id.row_view);
            this.clickListener = clickListener;
            v.setOnClickListener(this);
            v.setOnLongClickListener(this);
        }

        @Override
        public void onClick(View v) {
            if (clickListener != null) {
                clickListener.onItemClicked(getAdapterPosition());
            }
        }

        @Override
        public boolean onLongClick(View v) {
            return clickListener != null && clickListener.onItemLongClicked(getAdapterPosition());
        }
    }

    public interface ClickListener {
        void onItemClicked(int position);

        boolean onItemLongClicked(int position);
    }
} public class DTOConverter {


    public static List<ArtistDTO> getArtistList(List<Artist> artists) {
        List<ArtistDTO> artistDTOs = new ArrayList<>();
        for (Artist artist : artists) {
            artistDTOs.add(getArtistDTO(artist));
        }
        return artistDTOs;
    }

    public static ArtistDTO getArtistDTO(Artist artist) {
        ArtistDTO artistDTO = new ArtistDTO();
        artistDTO.setArtistName(artist.getArtistName());
        artistDTO.setCoverPath(artist.getCoverPath());
        artistDTO.setAlbums(getAlbumList(artist.getAlbums()));
        artistDTO.setId(artist.getId());
        return artistDTO;
    }


    private static List<AlbumDTO> getAlbumList(List<Album> albums) {
        List<AlbumDTO> albumDTOs = new ArrayList<>();
        for (Album album : albums) {
            albumDTOs.add(getAlbumDTO(album));
        }
        return albumDTOs;
    }

    private static AlbumDTO getAlbumDTO(Album album) {
        AlbumDTO albumDTO = new AlbumDTO();
        albumDTO.setAlbumTitle(album.getAlbumTitle());
        albumDTO.setCoverPath(album.getCoverPath());
        albumDTO.setSongs(getSongList(album.getSongs()));
        albumDTO.setId(album.getId());
        albumDTO.setArtistId(album.getId());
        return albumDTO;
    }

    public static List<SongDTO> getSongList(List<Song> songs) {
        List<SongDTO> songDTOs = new ArrayList<>();
        for (Song song : songs) {
            songDTOs.add(getSongDTO(song));
        }
        return songDTOs;
    }

    public static SongDTO getSongDTO(Song song) {
        SongDTO songDTO = new SongDTO();
        songDTO.setSongTitle(song.getSongTitle());
        songDTO.setSongDuration(song.getSongDuration());
        songDTO.setSongLocation(song.getSongLocation());
        songDTO.setAlbumId(song.getAlbumId());
        songDTO.setId(song.getId());
        return songDTO;
    }
} @RealmClass
public class Playlist extends RealmObject {
    private String id;
    private String playlistName;
    private RealmList<Song> songs;
    private String coverPath;

    public void setId(String id) {
        this.id = id;
    }

    public String getId() {
        return id;
    }


    public void setPlaylistName(String playlistName) {
        this.playlistName = playlistName;
    }

    public String getPlaylistName() {
        return playlistName;
    }


    public void setSongs(RealmList<Song> songs) {
        this.songs = songs;
    }

    public RealmList<Song> getSongs() {
        return songs;
    }

    public void setCoverPath(String coverPath) {
        this.coverPath = coverPath;
    }

    public String getCoverPath() {
        return coverPath;
    }
} @RealmClass
public class Song extends RealmObject {
    private String id;
    private String songTitle;
    private long songDuration;
    private String songLocation;
    private String albumId;
    private int noOfPlayed;
    private long lastPlayed;

    public void setId(String id) {
        this.id = id;
    }

    public String getId() {
        return id;
    }

    public void setSongTitle(String songTitle) {
        this.songTitle = songTitle;
    }

    public String getSongTitle() {
        return songTitle;
    }

    public void setSongDuration(long songDuration) {
        this.songDuration = songDuration;
    }

    public long getSongDuration() {
        return songDuration;
    }

    public void setSongLocation(String songLocation) {
        this.songLocation = songLocation;
    }

    public String getSongLocation() {
        return songLocation;
    }

    public void setAlbumId(String albumId) {
        this.albumId = albumId;
    }

    public String getAlbumId() {
        return albumId;
    }

    public void setNoOfPlayed(int noOfPlayed) {
        this.noOfPlayed = noOfPlayed;
    }

    public int getNoOfPlayed() {
        return noOfPlayed;
    }

    public void setLastPlayed(long lastPlayed) {
        this.lastPlayed = lastPlayed;
    }

    public long getLastPlayed() {
        return lastPlayed;
    }
} public class MusicContent implements Parcelable {

    private String playlistName;
    private String id;
    private ContentType contentType;

    public ContentType getContentType() {
        return contentType;
    }

    public void setContentType(ContentType contentType) {
        this.contentType = contentType;
    }

    public String getPlaylistName() {
        return playlistName;
    }

    public void setPlaylistName(String playlistName) {
        this.playlistName = playlistName;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(this.playlistName);
        dest.writeString(this.id);
        dest.writeInt(this.contentType == null ? -1 : this.contentType.ordinal());
    }

    public MusicContent() {
    }

    protected MusicContent(Parcel in) {
        this.playlistName = in.readString();
        this.id = in.readString();
        int tmpContentType = in.readInt();
        this.contentType = tmpContentType == -1 ? null : ContentType.values()[tmpContentType];
    }

    public static final Parcelable.Creator<MusicContent> CREATOR = new Parcelable.Creator<MusicContent>() {
        public MusicContent createFromParcel(Parcel source) {
            return new MusicContent(source);
        }

        public MusicContent[] newArray(int size) {
            return new MusicContent[size];
        }
    };
} public class SongDTO implements Parcelable {

    private String songTitle;
    private long songDuration;
    private String songLocation;
    private String albumId;
    private String id;

    public void setSongTitle(String songTitle) {
        this.songTitle = songTitle;
    }

    public String getSongTitle() {
        return songTitle;
    }

    public void setSongDuration(long songDuration) {
        this.songDuration = songDuration;
    }

    public long getSongDuration() {
        return songDuration;
    }

    public void setSongLocation(String songLocation) {
        this.songLocation = songLocation;
    }

    public String getSongLocation() {
        return songLocation;
    }

    public String getAlbumId() {
        return albumId;
    }

    public void setAlbumId(String albumId) {
        this.albumId = albumId;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getId() {
        return id;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(this.songTitle);
        dest.writeLong(this.songDuration);
        dest.writeString(this.songLocation);
        dest.writeString(this.albumId);
        dest.writeString(this.id);
    }

    public SongDTO() {
    }

    protected SongDTO(Parcel in) {
        this.songTitle = in.readString();
        this.songDuration = in.readLong();
        this.songLocation = in.readString();
        this.albumId = in.readString();
        this.id = in.readString();
    }

    public static final Parcelable.Creator<SongDTO> CREATOR = new Parcelable.Creator<SongDTO>() {
        public SongDTO createFromParcel(Parcel source) {
            return new SongDTO(source);
        }

        public SongDTO[] newArray(int size) {
            return new SongDTO[size];
        }
    };
} public interface PlaylistCallback {
    void playlistChosen(int position);
} public enum ContentType {
    ARTIST, ALBUM, PLAYLIST, MOST_PLAYED, LAST_PLAYED
} public class DialogHelper {
    public static void showAddPlaylistDialog(AppCompatActivity activity){
        FragmentManager manager = activity.getSupportFragmentManager();
        PlaylistAddDialog dialog = new PlaylistAddDialog();
        dialog.show(manager, "dialog");
    }

    public static void aboutDialog(final Context context){
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context, R.style.RhythmAlertDialog);
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View dialogView = inflater.inflate(R.layout.dialog_about_rhythm, null);
        PackageInfo pInfo;
        try {
            pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            TextView versionNameCode = (TextView)dialogView.findViewById(R.id.version_name_code);
            versionNameCode.setText(context.getResources().getString(R.string.version_name_code,
                    pInfo.versionName, pInfo.versionCode));
        } catch (PackageManager.NameNotFoundException e) {
            Timber.e(e, "packageInfo");
        }
        dialogView.findViewById(R.id.github_project).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(Intent.ACTION_VIEW);
                i.setData(Uri.parse("https://github.com/laithnurie/rhythm"));
                context.startActivity(i);
            }
        });
        dialogView.findViewById(R.id.design_page).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(Intent.ACTION_VIEW);
                i.setData(Uri.parse("https://dribbble.com/shots/2183234-Music-app-research"));
                context.startActivity(i);
            }
        });
        dialogBuilder.setView(dialogView);

        AlertDialog b = dialogBuilder.create();
        b.show();
    }

    public static void showPermissionDialog(final Context context){
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context, R.style.RhythmAlertDialog);
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View dialogView = inflater.inflate(R.layout.dialog_storage_permission, null);
        dialogBuilder.setView(dialogView);

        AlertDialog b = dialogBuilder.create();
        b.show();
    }

    public static void resetMusicDataAlert(final Context context) {
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context, R.style.RhythmAlertDialog);

        alertDialogBuilder.setTitle("Reset Music Data");
        alertDialogBuilder
                .setMessage("Including Most Played, Last Played and your Personal Playlists ?");
        alertDialogBuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                MusicDataUtility.resetMusicStats(context);
                SharedPreferences sharedPreferences = context
                        .getSharedPreferences("com.laithlab.rhythm", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putBoolean(context.getString(R.string.first_time_pref_key), true);
                editor.apply();
            }
        });
        alertDialogBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
            }
        });

        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();
    }

    public static void addSongToPlaylist(AppCompatActivity activity){
        List<Playlist> playlists = MusicDataUtility.getPlayists(activity);

        if(playlists.size() == 0){
            showAddPlaylistDialog(activity);
        } else {
            String[] playlistNames = new String[playlists.size()];
            for (int i = 0; i < playlistNames.length; i++) {
                playlistNames[i] = playlists.get(i).getPlaylistName();
            }
            FragmentManager manager = activity.getSupportFragmentManager();
            PlaylistSelectDialog dialog = new PlaylistSelectDialog();
            Bundle args = new Bundle();
            args.putStringArray("playlistNames", playlistNames);
            dialog.setArguments(args);
            dialog.show(manager, "dialog");
        }
    }
} public class MusicDataUtility {

    private static boolean isUpdating = false;

    // Constructor
    public MusicDataUtility() {
    }

    private static void getMusicContent(Context context) {
        getMusicContentByUri(context, MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);
        getMusicContentByUri(context, MediaStore.Audio.Media.INTERNAL_CONTENT_URI);
    }

    private static void getMusicContentByUri(Context context, Uri contentUri) {
        ContentResolver cr = context.getContentResolver();

        String selection = MediaStore.Audio.Media.IS_MUSIC + "!= 0";
        String sortOrder = MediaStore.Audio.Media.TITLE + " ASC";
        Cursor cur = cr.query(contentUri, null, selection, null, sortOrder);
        int count;

        if (cur != null) {
            count = cur.getCount();

            if (count > 0) {
                while (cur.moveToNext()) {
                    String data = cur.getString(cur.getColumnIndex(MediaStore.Audio.Media.DATA));
                    createSongEntry(context, data);
                }
            }
            cur.close();
        }
    }

    public static byte[] getImageData(String songLocation) {
        File songFile = new File(songLocation);
        if (songFile.exists()) {
            return new MusicMetaData(songLocation).getAlbumArt();
        }
        return null;
    }

    public static RhythmSong getSongMeta(String songLocation) {
        MusicMetaData musicMetaData = new MusicMetaData(songLocation);
        String artist = musicMetaData.getArtistName() != null ? musicMetaData.getArtistName() : "Unknown Artist";
        String album = musicMetaData.getAlbumName() != null ? musicMetaData.getAlbumName() : "Unknown Album";
        String track = musicMetaData.getSongTitle() != null ? musicMetaData.getSongTitle() : "Unknown Track";
        byte[] imageData = musicMetaData.getAlbumArt();
        long duration = musicMetaData.getDuration() / 1000;
        return new RhythmSong.RhythmSongBuilder().songLocation(songLocation).artistTitle(artist).albumTitle(album)
                .trackTitle(track).imageData(imageData).duration(duration).build();
    }

    public static List<SearchResult> getAllSearchResults(Context context) {
        List<SearchResult> results = new ArrayList<>();
        List<Artist> artists = allArtists(context);
        for (Artist artist : artists) {
            results.add(createSearchResult(artist.getId(), artist.getArtistName(), artist.getAlbums().size() + " albums", SearchResult.ResultType.ARTIST));
            for (Album album : artist.getAlbums()) {
                results.add(createSearchResult(album.getId(), album.getAlbumTitle(), artist.getArtistName(), SearchResult.ResultType.ALBUM));
                for (Song song : album.getSongs()) {
                    results.add(createSearchResult(song.getId(), song.getSongTitle(),
                            artist.getArtistName() + " - " + album.getAlbumTitle()
                            , SearchResult.ResultType.SONG));
                }
            }
        }
        Collections.sort(results, new Comparator<SearchResult>() {
            @Override
            public int compare(SearchResult lhs, SearchResult rhs) {
                return lhs.getResultType().compareTo(rhs.getResultType());
            }
        });
        int lastIndexOfArtists = 0;
        int lastIndexOfAlbums = 0;
        SearchResult.ResultType resultType;
        for (int i = 0; i < results.size(); i++) {
            resultType = results.get(i).getResultType();
            if (resultType == SearchResult.ResultType.ARTIST) {
                lastIndexOfArtists = i;
            } else if (resultType == SearchResult.ResultType.ALBUM) {
                lastIndexOfAlbums = i;
            }
        }
        if (results.size() > 0) {
            results.add(0, createSearchResult(null, "Artists", null, SearchResult.ResultType.HEADER));
            results.add(lastIndexOfArtists + 2, createSearchResult(null, "Albums", null, SearchResult.ResultType.HEADER));
            results.add(lastIndexOfAlbums + 3, createSearchResult(null, "Songs", null, SearchResult.ResultType.HEADER));
            return results;
        } else {
            return null;
        }
    }

    private static SearchResult createSearchResult(String id, String mainTitle, String subTitle, SearchResult.ResultType resultType) {
        return new SearchResult.SearchResultBuilder().id(id).mainTitle(mainTitle).subTitle(subTitle).setResultType(resultType).build();
    }

    public static void updateMusicDB(Context context) {
        if (!isUpdating) {
            isUpdating = true;
            getMusicContent(context);
            isUpdating = false;
        }
    }

    private static void createSongEntry(Context context, String songPath) {
        RhythmSong songEntry = getSongMeta(songPath);

        Realm realm = Realm.getInstance(context);
        realm.beginTransaction();
        Artist artistRecord = getOrCreateArtist(realm, songEntry);
        Album albumRecord = getOrCreateAlbum(realm, artistRecord, songEntry);
        getOrCreateSong(realm, albumRecord, songEntry.getTrackTitle(), songEntry.getDuration(), songPath);
        realm.commitTransaction();
        realm.close();
    }

    private static Artist getOrCreateArtist(Realm realm, RhythmSong rhythmSong) {
        if (rhythmSong.getArtistTitle().equals("Untitled Artist")) {
            Artist query = realm.where(Artist.class)
                    .contains("artistName", "Untitled Artist")
                    .findFirst();
            if (query != null) {
                return query;
            } else {
                Artist newArtist = realm.createObject(Artist.class);
                newArtist.setArtistName("Untitled Artist");
                if (rhythmSong.getImageData() != null) {
                    newArtist.setCoverPath(rhythmSong.getSongLocation());
                }
                newArtist.setId(UUID.randomUUID().toString());
                return newArtist;
            }
        } else {
            Artist query = realm.where(Artist.class)
                    .contains("artistName", rhythmSong.getArtistTitle())
                    .findFirst();
            if (query != null) {
                return query;
            } else {
                Artist newArtist = realm.createObject(Artist.class);
                newArtist.setArtistName(rhythmSong.getArtistTitle());
                if (rhythmSong.getImageData() != null) {
                    newArtist.setCoverPath(rhythmSong.getSongLocation());
                }
                newArtist.setId(UUID.randomUUID().toString());
                return newArtist;
            }
        }
    }

    private static Album getOrCreateAlbum(Realm realm, Artist artistRecord, RhythmSong rhythmSong) {
        Album albumRecord = null;
        if (rhythmSong.getAlbumTitle() == null) {
            for (Album albumItem : artistRecord.getAlbums()) {
                if (albumItem.getAlbumTitle().equals("Untitled Album")) {
                    albumRecord = albumItem;
                }
            }
            if (albumRecord != null) {
                return albumRecord;
            } else {
                albumRecord = realm.createObject(Album.class);
                albumRecord.setAlbumTitle("Untitled Album");
                albumRecord.setId(UUID.randomUUID().toString());
                albumRecord.setArtistId(artistRecord.getId());
                if (rhythmSong.getImageData() != null) {
                    albumRecord.setCoverPath(rhythmSong.getSongLocation());
                }
                artistRecord.getAlbums().add(albumRecord);
                return albumRecord;
            }
        } else {
            for (Album albumItem : artistRecord.getAlbums()) {
                if (albumItem.getAlbumTitle().equals(rhythmSong.getAlbumTitle())) {
                    albumRecord = albumItem;
                }
            }
            if (albumRecord != null) {
                return albumRecord;
            } else {
                albumRecord = realm.createObject(Album.class);
                albumRecord.setAlbumTitle(rhythmSong.getAlbumTitle());
                albumRecord.setId(UUID.randomUUID().toString());
                albumRecord.setArtistId(artistRecord.getId());
                if (rhythmSong.getImageData() != null) {
                    albumRecord.setCoverPath(rhythmSong.getSongLocation());
                }
                artistRecord.getAlbums().add(albumRecord);
                return albumRecord;
            }
        }
    }

    private static void getOrCreateSong(Realm realm, Album albumRecord, String songTitle, long duration, String songPath) {
        Song songRecord = null;
        for (Song songItem : albumRecord.getSongs()) {
            if (songItem.getSongLocation().equals(songPath)) {
                songRecord = songItem;
            }
        }
        if (songRecord == null) {
            songRecord = realm.createObject(Song.class);
            songRecord.setId(UUID.randomUUID().toString());
            songRecord.setSongTitle(songTitle != null ? songTitle : "Untitled Song");
            songRecord.setAlbumId(albumRecord.getId());
            songRecord.setSongLocation(songPath);
            if (duration > 0) {
                songRecord.setSongDuration(duration);
            }
            albumRecord.getSongs().add(songRecord);
        }

    }

    public static List<Artist> allArtists(Context context) {
        Realm realm = Realm.getInstance(context);
        return realm.allObjects(Artist.class);
    }

    public static List<Song> getAllSongs(Context context) {
        Realm realm = Realm.getInstance(context);
        return realm.allObjects(Song.class);
    }

    private static List<Song> getLastPlayedSongs(Context context) {
        Realm realm = Realm.getInstance(context);
        RealmResults<Song> result = realm.where(Song.class).greaterThan("lastPlayed", 0).findAll();
        result.sort("lastPlayed", Sort.DESCENDING);
        return result;
    }

    private static List<Song> getMostPlayedSongs(Context context) {
        Realm realm = Realm.getInstance(context);
        RealmResults<Song> result = realm.where(Song.class).greaterThan("noOfPlayed", 0).findAll();
        result.sort("noOfPlayed", Sort.DESCENDING);
        return result;
    }

    public static List<Playlist> getPlayists(Context context) {
        Realm realm = Realm.getInstance(context);
        return realm.allObjects(Playlist.class);
    }

    public static Song getSongById(String id, Context context) {
        Realm realm = Realm.getInstance(context);
        realm.beginTransaction();
        Song song = realm.where(Song.class)
                .contains("id", id)
                .findFirst();
        realm.commitTransaction();
        realm.close();
        return song;
    }

    private static Album getAlbumById(String id, Context context) {
        Realm realm = Realm.getInstance(context);
        realm.beginTransaction();
        Album album = realm.where(Album.class)
                .contains("id", id)
                .findFirst();
        realm.commitTransaction();
        realm.close();
        return album;
    }

    public static Artist getArtistById(String id, Context context) {
        Realm realm = Realm.getInstance(context);
        realm.beginTransaction();
        Artist artist = realm.where(Artist.class)
                .contains("id", id)
                .findFirst();
        realm.commitTransaction();
        realm.close();
        return artist;
    }

    private static Playlist getPlaylistById(String id, Context context) {
        Realm realm = Realm.getInstance(context);
        realm.beginTransaction();
        Playlist playlist = realm.where(Playlist.class)
                .contains("id", id)
                .findFirst();
        realm.commitTransaction();
        realm.close();
        return playlist;
    }

    public static List<Song> getSongsFromList(MusicContent musicContent, Context context) {
        switch (musicContent.getContentType()) {
            case ARTIST:
                //TODO: get all songs from artist
                return getArtistById(musicContent.getId(), context).getAlbums().get(0).getSongs();
            case ALBUM:
                return getAlbumById(musicContent.getId(), context).getSongs();
            case PLAYLIST:
                return getPlaylistById(musicContent.getId(), context).getSongs();
            case MOST_PLAYED:
                return getMostPlayedSongs(context);
            case LAST_PLAYED:
                return getLastPlayedSongs(context);
        }

        return null;
    }

    public static void createPlaylist(String playlistName, Context context) {
        Realm realm = Realm.getInstance(context);
        realm.beginTransaction();

        Playlist playlistRecord = realm.createObject(Playlist.class);
        playlistRecord.setId(UUID.randomUUID().toString());
        playlistRecord.setPlaylistName(playlistName);

        realm.commitTransaction();
        realm.close();
    }

    public static void deletePlaylist(String playlistID, Context context) {
        Realm realm = Realm.getInstance(context);
        realm.beginTransaction();

        Playlist playlistToDelete = realm.where(Playlist.class)
                .equalTo("id", playlistID)
                .findFirst();
        playlistToDelete.removeFromRealm();
        realm.commitTransaction();
        realm.close();
    }

    public static void updateSongCount(String songId, Context context) {
        Realm realm = Realm.getInstance(context);
        realm.beginTransaction();
        Song song = realm.where(Song.class)
                .contains("id", songId)
                .findFirst();
        song.setNoOfPlayed(song.getNoOfPlayed() + 1);
        song.setLastPlayed(System.currentTimeMillis());

        realm.commitTransaction();
        realm.close();
    }

    public static void resetMusicStats(Context context) {
        Realm realm = Realm.getInstance(context);
        realm.beginTransaction();
        realm.where(Artist.class).findAll().clear();
        realm.where(Album.class).findAll().clear();
        realm.where(Song.class).findAll().clear();
        realm.where(Playlist.class).findAll().clear();
        realm.commitTransaction();
        realm.close();
    }
} public class ViewUtils {
    public static void drawerClickListener(final Activity activity) {

        View.OnClickListener clickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int i = v.getId();
                if (i == R.id.browse_drawer_item) {
                    Intent browse = new Intent(activity, BrowseActivity.class);
                    activity.startActivity(browse);
                } else if (i == R.id.most_played_drawer_item) {
                    Intent mostPlayed = new Intent(activity, PlaylistActivity.class);
                    MusicContent musicContent = new MusicContent();
                    musicContent.setContentType(ContentType.MOST_PLAYED);
                    musicContent.setPlaylistName("Most Played");
                    mostPlayed.putExtra("musicContent", musicContent);
                    activity.startActivity(mostPlayed);
                } else if (i == R.id.last_played_drawer_item) {
                    Intent lastPlayed = new Intent(activity, PlaylistActivity.class);
                    MusicContent musicContent = new MusicContent();
                    musicContent.setContentType(ContentType.LAST_PLAYED);
                    musicContent.setPlaylistName("Last Played");
                    lastPlayed.putExtra("musicContent", musicContent);
                    activity.startActivity(lastPlayed);
                } else if (i == R.id.playlists_drawer_item) {
                    Intent playlists = new Intent(activity, PlaylistGridActivity.class);
                    activity.startActivity(playlists);
                } else if (i == R.id.now_playing_drawer_item) {
                    Intent playerIntent = new Intent(activity, SwipePlayerActivity.class);
                    playerIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    activity.startActivity(playerIntent);
                } else if (i == R.id.settings_drawer_item) {
                    Intent settings = new Intent(activity, RhythmPrefs.class);
                    activity.startActivity(settings);
                }
            }
        };

        activity.findViewById(R.id.browse_drawer_item).setOnClickListener(clickListener);
        activity.findViewById(R.id.most_played_drawer_item).setOnClickListener(clickListener);
        activity.findViewById(R.id.last_played_drawer_item).setOnClickListener(clickListener);
        activity.findViewById(R.id.playlists_drawer_item).setOnClickListener(clickListener);
        activity.findViewById(R.id.now_playing_drawer_item).setOnClickListener(clickListener);
        activity.findViewById(R.id.settings_drawer_item).setOnClickListener(clickListener);

        activity.findViewById(R.id.now_playing_drawer_item).setVisibility(PlayBackUtil.getMediaPlayer() != null ? View.VISIBLE : View.GONE);
    }
}
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.view.ActionMode;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import com.laithlab.rhythm.R;
import com.laithlab.rhythm.adapter.SongListAdapter;
import com.laithlab.rhythm.converter.DTOConverter;
import com.laithlab.rhythm.db.Playlist;
import com.laithlab.rhythm.db.Song;
import com.laithlab.rhythm.dto.MusicContent;
import com.laithlab.rhythm.dto.SongDTO;
import com.laithlab.rhythm.fragment.PlaylistCallback;
import com.laithlab.rhythm.utils.ContentType;
import com.laithlab.rhythm.utils.DialogHelper;
import com.laithlab.rhythm.utils.MusicDataUtility;
import com.laithlab.rhythm.utils.ViewUtils;
import java.util.ArrayList;
import java.util.List;
import io.realm.Realm;
import io.realm.RealmList;
package com.laithlab.rhythm.activity;





public class PlaylistActivity extends RhythmActivity implements SongListAdapter.ClickListener
        , PlaylistCallback, PlaylistAddCallback {

    public static String MUSIC_CONTENT = "musicContent";

    private DrawerLayout drawerLayout;

    private SongListAdapter songListAdapter;

    private MusicContent musicContent;
    private List<SongDTO> songs;

    private ActionModeCallback actionModeCallback;
    private ActionMode actionMode;

    public static Intent getIntent(Context context, MusicContent musicContent) {
        Intent artistActivity = new Intent(context, PlaylistActivity.class);
        artistActivity.putExtra(MUSIC_CONTENT, musicContent);
        return artistActivity;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_playlist);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        final ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            getSupportActionBar().setDisplayShowTitleEnabled(false);
            actionBar.setHomeAsUpIndicator(R.drawable.ic_menu_white_24dp);
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
        Bundle extras = getIntent().getExtras();
        musicContent = extras.getParcelable(MUSIC_CONTENT);
        if (musicContent != null) {
            actionModeCallback = new ActionModeCallback(musicContent.getContentType());
        }

        TextView albumTitle = (TextView) findViewById(R.id.txt_album);
        albumTitle.setText(musicContent.getPlaylistName());

        drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawerLayout.setStatusBarBackgroundColor(getResources().getColor(R.color.color_primary));

        RecyclerView songList = (RecyclerView) findViewById(R.id.rv_songs_list);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        songList.setLayoutManager(layoutManager);

        songs = DTOConverter.getSongList(MusicDataUtility.getSongsFromList(musicContent, this));