package fi.metropolia.yellow_spaceship.androidadvproject.api;

import android.content.ContentValues;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.AsyncTask;

import com.squareup.okhttp.Call;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import fi.metropolia.yellow_spaceship.androidadvproject.models.DAMSound;
import fi.metropolia.yellow_spaceship.androidadvproject.database.DAMSoundContract.DAMSoundEntry;
import fi.metropolia.yellow_spaceship.androidadvproject.providers.SoundContentProvider;

/**
 * Downloads a sound asyncronously
 */
public class AsyncDownloader extends AsyncTask<Void, Long, Boolean> {

    private DAMSound mDAMSound;
    private Context mContext;
    private File mFile;
    private File mFolder;

    /**
     * Constructor, sets the file url.
     * @param damSound DAMSound for the file we are downloading
     * @param context Activity context
     */
    public AsyncDownloader(DAMSound damSound, Context context) {

        mDAMSound = damSound;
        mContext = context;

    }

    @Override
    protected Boolean doInBackground(Void... params) {

        OkHttpClient httpClient = new OkHttpClient();

        Call call = httpClient.newCall(new Request.Builder().url(mDAMSound.getDownloadLink()).get().build());

        try {

            Response response = call.execute();

            if(response.code() == 200) {

                InputStream inputStream = null;
                OutputStream outputStream = null;

                try {

                    mFolder = new File(mContext.getFilesDir() + "/sounds");
                    if(!mFolder.exists()) {
                        mFolder.mkdirs();
                    }

                    mFile = new File(mFolder, mDAMSound.getFormattedSoundId() + "." + mDAMSound.getFileExtension());
                    inputStream = response.body().byteStream();
                    outputStream = new FileOutputStream(mFile);

                    byte[] buffer = new byte[1024 * 4];
                    long downloaded = 0;
                    long totalSize = response.body().contentLength();
                    publishProgress(0L, totalSize);

                    int len;
                    while((len = inputStream.read(buffer)) > 0) {

                        outputStream.write(buffer, 0, len);

                        downloaded += len;
                        publishProgress(downloaded, totalSize);

                        // Stop the task and return false, if cancel() is called.
                        if (isCancelled())
                            return false;


                    }

                    return downloaded == totalSize;

                } catch(IOException ioE) {

                    return false;

                } finally {

                    if(inputStream != null) {

                        inputStream.close();

                    }

                    if(outputStream != null) {

                        outputStream.close();

                    }

                }

            } else {

                return false;

            }

        } catch (IOException e) {

            e.printStackTrace();
            return false;

        }

    }

    @Override
    protected void onProgressUpdate(Long... values) {

        float percentage = (float)values[0] / (float)values[1] * 100;
        System.out.println(percentage);

    }

    @Override
    protected void onPostExecute(Boolean result) {

        // Playing the sound after download (for now)
        if(result) {

            setFileMetaData();

            MediaPlayer mp = new MediaPlayer();
            try {
                mp.setDataSource(mFile.getAbsolutePath());
                mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
                mp.prepare();
                mp.start();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }

    @Override
    protected void onPreExecute() {

        if(mDAMSound != null) {

            String filename = mDAMSound.getFileName();

            if(filename != null) {
                System.out.println("File has been already downloaded!");
                this.cancel(true);
            }

        }

    }

    /**
     * Set meta data for the sound file.
     * Saves the state in our ContentProvider
     */
    private void setFileMetaData() {

        if (mDAMSound != null) {
            mDAMSound.setFileName(mFile.getName());

            ContentValues values = new ContentValues();
            values.put(DAMSoundEntry.COLUMN_NAME_SOUND_ID, mDAMSound.getFormattedSoundId());
            values.put(DAMSoundEntry.COLUMN_NAME_TITLE, mDAMSound.getTitle());
            values.put(DAMSoundEntry.COLUMN_NAME_CATEGORY, mDAMSound.getCategory().toString());
            values.put(DAMSoundEntry.COLUMN_NAME_TYPE, mDAMSound.getSoundType().toString());
            values.put(DAMSoundEntry.COLUMN_NAME_LENGTH_SEC, mDAMSound.getLengthSec());
            values.put(DAMSoundEntry.COLUMN_NAME_IS_FAVORITE, mDAMSound.getIsFavorite());
            values.put(DAMSoundEntry.COLUMN_NAME_FILE_NAME, mDAMSound.getFileName());

            // Insert or update meta data, depending on whether the sound already exists
            // in the database.
            mContext.getContentResolver().insert(SoundContentProvider.CONTENT_URI, values);

            //mRecyclerView.getAdapter().notifyDataSetChanged();
        }
    }

}

@@ -130,77 +130,8 @@
 xt;%0A
-import android.media.AudioManager;%0Aimport android.media.MediaPlayer;%0A
 impo
@@ -3752,347 +3752,8 @@
 );%0A%0A
-            MediaPlayer mp = new MediaPlayer();%0A            try %7B%0A                mp.setDataSource(mFile.getAbsolutePath());%0A                mp.setAudioStreamType(AudioManager.STREAM_MUSIC);%0A                mp.prepare();%0A                mp.start();%0A            %7D catch (IOException e) %7B%0A                e.printStackTrace();%0A            %7D%0A%0A
     

Remove MediaPlayer playback from AsyncDownloader