<commit_before>package com.jrvermeer.psalter;

import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.AssetFileDescriptor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v7.app.NotificationCompat;
import android.widget.Toast;

import com.jrvermeer.psalter.Models.Psalter;

import java.util.Random;

/**
 * Created by Jonathan on 4/3/2017.
 */

public class MediaService extends Service implements AudioManager.OnAudioFocusChangeListener, MediaPlayer.OnCompletionListener {
    private MediaBinder mBinder = new MediaBinder();
    private IMediaCallbacks mediaCallbacks = null;

    private PsalterDb db;
    private AudioManager audioManager;
    private MediaPlayer mediaPlayer = new MediaPlayer();
    private State mState = null;
    private Random rand = new Random();

    private final int MS_BETWEEN_VERSES = 700;
    private final int NOTIFICATION_ID = 1234;
    private final String ACTION = "action";
    private static int ACTION_STOP = 1;
    private static int ACTION_NEXT = 2;
    private static int ACTION_PLAY = 3;

    @Override
    public void onCreate() {
        audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
        db = new PsalterDb(this);
        registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if(intent.getAction().equals(AudioManager.ACTION_AUDIO_BECOMING_NOISY)){
                    stopMedia(false);
                }
            }
        }, new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY));
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if(intent != null ){
            int action = intent.getIntExtra(ACTION, -1);
            if(action == ACTION_STOP && isPlaying()){
                stopMedia(false);
            }
            else if(action == ACTION_NEXT){
                playRandomNumber();
            }
            else if(action == ACTION_PLAY && !isPlaying()){
                if(mState != null) playPsalter(mState);
            }
        }
        stopSelf();
        return START_NOT_STICKY;
    }

    public void setCallbacks(@NonNull final IMediaCallbacks callbacks){
        mediaCallbacks = callbacks;
    }

    public void playPsalterNumber(int number){
        Psalter psalter = db.getPsalter(number);
        playPsalter(new State(psalter, false));
    }
    public void shuffleAllAudio(int firstNumber){
        Psalter psalter = db.getPsalter(firstNumber);
        playPsalter(new State(psalter, true));
        Toast.makeText(this, "Shuffling", Toast.LENGTH_SHORT).show();
    }
    private void playRandomNumber(){
        int nextIndex = rand.nextInt(db.getCount());
        Psalter psalter = db.getPsalter(nextIndex + 1);
        playPsalter(new State(psalter, true));
        if(mediaCallbacks != null){
            mediaCallbacks.setCurrentNumber(psalter.getNumber());
        }
    }
    private boolean playPsalter(@NonNull State state){
        try{
            if(audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN) == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
                mediaPlayer.reset();
                mState = state;
                AssetFileDescriptor afd = getAssetFileDescriptor(mState.psalter);
                mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
                afd.close();
                mediaPlayer.setOnCompletionListener(this);
                mediaPlayer.prepare();
                mediaPlayer.start();
                if(mediaCallbacks != null) mediaCallbacks.playerStarted();
                startForeground(NOTIFICATION_ID, getNotification());
                return true;
            }
            else return false;
        }
        catch(Exception ex) {
            return false;
        }
    }
    private boolean playNextVerse(){
        mState.currentVerse++;
        if(mState.currentVerse <= mState.psalter.getNumverses()){
            mState.betweenVerses = true;
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if(mState != null && mState.betweenVerses){ // media could have been stopped between verses
                        mediaPlayer.start();
                        startForeground(NOTIFICATION_ID, getNotification());
                        mState.betweenVerses = false;
                    }
                }
            }, MS_BETWEEN_VERSES);
            return true;
        }
        return false;
    }

    @Override
    public void onCompletion(MediaPlayer mediaPlayer) {
        if(!playNextVerse()){
            if(mState.isShuffling){
                playRandomNumber();
            }
            else playbackStopped(true);
        }
    }

    private AssetFileDescriptor getAssetFileDescriptor(Psalter psalter) {
        int resID = getResources().getIdentifier(psalter.getAudioFileName(), "raw", getPackageName());
        return getApplicationContext().getResources().openRawResourceFd(resID);
    }

    public void stopMedia(){
        stopMedia(true);
    }
    private void stopMedia(boolean removeNotification){
        if(mediaPlayer.isPlaying()) mediaPlayer.stop();
        playbackStopped(removeNotification);
    }

    public boolean isPlaying(int number){
        return isPlaying() && mState.psalter.getNumber() == number;
    }
    public boolean isPlaying(){
        return mediaPlayer.isPlaying() || (mState != null && mState.betweenVerses);
    }

    private void playbackStopped(boolean removeNotification){

        stopForeground(removeNotification);
        if(removeNotification) mState = null;
        else {
            mState.betweenVerses = false;
            NotificationManagerCompat.from(this).notify(NOTIFICATION_ID, getNotification());
        }

        audioManager.abandonAudioFocus(this);<commit_msg>Hopefully fix nullpointerexception<commit_after>package com.jrvermeer.psalter;

import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.AssetFileDescriptor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v7.app.NotificationCompat;
import android.widget.Toast;

import com.jrvermeer.psalter.Models.Psalter;

import java.util.Random;

/**
 * Created by Jonathan on 4/3/2017.
 */

public class MediaService extends Service implements AudioManager.OnAudioFocusChangeListener, MediaPlayer.OnCompletionListener {
    private MediaBinder mBinder = new MediaBinder();
    private IMediaCallbacks mediaCallbacks = null;

    private PsalterDb db;
    private AudioManager audioManager;
    private MediaPlayer mediaPlayer = new MediaPlayer();
    private State mState = null;
    private Random rand = new Random();

    private final int MS_BETWEEN_VERSES = 700;
    private final int NOTIFICATION_ID = 1234;
    private final String ACTION = "action";
    private static int ACTION_STOP = 1;
    private static int ACTION_NEXT = 2;
    private static int ACTION_PLAY = 3;

    @Override
    public void onCreate() {
        audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
        db = new PsalterDb(this);
        registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if(intent.getAction().equals(AudioManager.ACTION_AUDIO_BECOMING_NOISY)){
                    stopMedia(false);
                }
            }
        }, new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY));
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if(intent != null ){
            int action = intent.getIntExtra(ACTION, -1);
            if(action == ACTION_STOP && isPlaying()){
                stopMedia(false);
            }
            else if(action == ACTION_NEXT){
                playRandomNumber();
            }
            else if(action == ACTION_PLAY && !isPlaying()){
                if(mState != null) playPsalter(mState);
            }
        }
        stopSelf();
        return START_NOT_STICKY;
    }

    public void setCallbacks(@NonNull final IMediaCallbacks callbacks){
        mediaCallbacks = callbacks;
    }

    public void playPsalterNumber(int number){
        Psalter psalter = db.getPsalter(number);
        playPsalter(new State(psalter, false));
    }
    public void shuffleAllAudio(int firstNumber){
        Psalter psalter = db.getPsalter(firstNumber);
        playPsalter(new State(psalter, true));
        Toast.makeText(this, "Shuffling", Toast.LENGTH_SHORT).show();
    }
    private void playRandomNumber(){
        int nextIndex = rand.nextInt(db.getCount());
        Psalter psalter = db.getPsalter(nextIndex + 1);
        playPsalter(new State(psalter, true));
        if(mediaCallbacks != null){
            mediaCallbacks.setCurrentNumber(psalter.getNumber());
        }
    }
    private boolean playPsalter(@NonNull State state){
        try{
            if(audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN) == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
                mediaPlayer.reset();
                mState = state;
                AssetFileDescriptor afd = getAssetFileDescriptor(mState.psalter);
                mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
                afd.close();
                mediaPlayer.setOnCompletionListener(this);
                mediaPlayer.prepare();
                mediaPlayer.start();
                if(mediaCallbacks != null) mediaCallbacks.playerStarted();
                startForeground(NOTIFICATION_ID, getNotification());
                return true;
            }
            else return false;
        }
        catch(Exception ex) {
            return false;
        }
    }
    private boolean playNextVerse(){
        mState.currentVerse++;
        if(mState.currentVerse <= mState.psalter.getNumverses()){
            mState.betweenVerses = true;
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if(mState != null && mState.betweenVerses){ // media could have been stopped between verses
                        mediaPlayer.start();
                        startForeground(NOTIFICATION_ID, getNotification());
                        mState.betweenVerses = false;
                    }
                }
            }, MS_BETWEEN_VERSES);
            return true;
        }
        return false;
    }

    @Override
    public void onCompletion(MediaPlayer mediaPlayer) {
        if(!playNextVerse()){
            if(mState.isShuffling){
                playRandomNumber();
            }
            else playbackStopped(true);
        }
    }

    private AssetFileDescriptor getAssetFileDescriptor(Psalter psalter) {
        int resID = getResources().getIdentifier(psalter.getAudioFileName(), "raw", getPackageName());
        return getApplicationContext().getResources().openRawResourceFd(resID);
    }

    public void stopMedia(){
        stopMedia(true);
    }
    private void stopMedia(boolean removeNotification){
        if(mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
            playbackStopped(removeNotification);
        }
    }

    public boolean isPlaying(int number){
        return isPlaying() && mState.psalter.getNumber() == number;
    }
    public boolean isPlaying(){
        return mediaPlayer.isPlaying() || (mState != null && mState.betweenVerses);
    }

    private void playbackStopped(boolean removeNotification){

        stopForeground(removeNotification);
        if(removeNotification) mState = null;
        else {
            mState.betweenVerses = false;
            NotificationManagerCompat.from(this).notify(NOTIFICATION_ID, getNotification());
        }

        audioManager.abandonAudioFocus(this);
{'fraction_non_alphanumeric': 0.0928205520299717, 'fraction_numerical': 0.0030583377934092822, 'mean_word_length': 2.487070114636097, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3629668', 'n_tokens_mistral': 3575, 'n_tokens_neox': 3399, 'n_words': 715}