package com.mybigday.rnmediaplayer;

import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;

import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;

public class AudioPlayer {
    private Context context;
    private ReactApplicationContext reactContext;
    private Map<String, MediaPlayer> audioIdMap = new HashMap<String, MediaPlayer>();

    public AudioPlayer(Context context, ReactApplicationContext reactContext) {
        this.context = context;
        this.reactContext = reactContext;
    }

    public WritableMap playMusic(String filePath) {
        MediaPlayer mediaPlayer = MediaPlayer.create(context, Uri.parse(filePath));
        mediaPlayer.start();

        String id = UUID.randomUUID().toString();
        audioIdMap.put(id, mediaPlayer);

        WritableMap evt = Arguments.createMap();
        evt.putString("musicId", id);
        sendEvent("MusicStart", evt);

        int duration = mediaPlayer.getDuration();
        WritableMap result = Arguments.createMap();
        result.putString("id", id);
        result.putInt("duration", duration);
        return result;
    }

    public void stopMusic(String id) {
        MediaPlayer mediaPlayer = audioIdMap.get(id);
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            audioIdMap.remove(id);
        }
    }

    public void stopAllMusic() {
        Iterator it = audioIdMap.entrySet().iterator();
        while (it.hasNext()) {
            MediaPlayer mediaPlayer = (MediaPlayer) it.next();
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.stop();
            }
            mediaPlayer.release();
            it.remove();
        }
    }

    protected void sendEvent(String eventName, WritableMap params) {
        reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
                .emit(eventName, params);
    }
}

@@ -121,16 +121,73 @@
 t.Uri;%0A%0A
+import com.facebook.react.bridge.LifecycleEventListener;%0A
 import c
@@ -222,16 +222,16 @@
 uments;%0A
-
 import c
@@ -516,16 +516,50 @@
 oPlayer 
+implements LifecycleEventListener 
 %7B%0A    pr
@@ -826,24 +826,24 @@
  = context;%0A
-
         this
@@ -867,24 +867,79 @@
 eactContext;
+%0A%0A        reactContext.addLifecycleEventListener(this);
 %0A    %7D%0A%0A    
@@ -2334,11 +2334,187 @@
 );%0A    %7D
+%0A%0A    @Override%0A    public void onHostResume() %7B%7D%0A%0A    @Override%0A    public void onHostPause() %7B%0A        stopAllMusic();%0A    %7D%0A%0A    @Override%0A    public void onHostDestroy() %7B%7D
 %0A%7D%0A

Implement LifecycleEventListener for AudioPlayer