package com.netfluke.sergey.purringservice;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.os.AsyncTask;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.temporal.ChronoUnit;

import static java.lang.System.currentTimeMillis;

public class MyService extends Service {

    Context ctx = this;
    MediaPlayer mediaPlayer;
    enum Status { RUNNING, IDLE };
    Status st = Status.IDLE;

    // Instant time0, time1;  API >= 26
    long time0, time1;

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // We want this service to continue running until it is explicitly
        // stopped, so return sticky.

        /* This bogs down the UI thread, and eventually kills the app. This is because
            Service still runs in the main UI thread. It needs an AsyncTask to be done right.
        try {
            Thread.sleep(5000);
        }
        catch (InterruptedException e){
            // pass
        }*/

        if( st == Status.RUNNING ){
            Toast.makeText(this, "Service Already Running", Toast.LENGTH_LONG).show();
            return START_NOT_STICKY;
        }
        else {
            st = Status.RUNNING;
            // time0 = Instant.now();  API >= 26
            time0 = currentTimeMillis();

            Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();

            new PlayBackgroudPurr().execute("purr");

            // If we get killed, after returning from here, restart
            return START_STICKY;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // time1 = Instant.now();   API >= 26
        time1 = currentTimeMillis();

        mediaPlayer.stop();
        mediaPlayer.reset();   // "mediaplayer went away with unhandled events" otherwise
        mediaPlayer.release(); // "mediaplayer finalized without being released" otherwise
        mediaPlayer = null;

        Toast.makeText(this, "Service Destroyed, purred for " +
                 // ChronoUnit.SECONDS.between(time0,time1) + " secs "
                        (time1 - time0)/1000 + " secs"
                , Toast.LENGTH_LONG).show();
    }

    private class PlayBackgroudPurr extends AsyncTask<String, Void, String> {
        SoundPool soundPool;
        int soundID;
        float volume = 1.0f;

        @Override
        protected String doInBackground(String... strings) {
            // getApplicationContext().setVolumeControlStream(AudioManager.STREAM_MUSIC);

            /* // This cuts out after a few seconds of play. Here's why:
               //  https://stackoverflow.com/questions/13377604/soundpool-plays-only-first-5-secs-of-file-why
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                soundPool = new SoundPool.Builder().build();
            } else {
                soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
            }

            soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
                @Override
                public void onLoadComplete(SoundPool soundPool, int i, int i1) {
                    soundPool.play(soundID, volume, volume, 1, 0, 1f);
                    Log.d("SND", "returning");
                }
            });

            soundID = soundPool.load(ctx, R.raw.purrs, 1);
            */

            mediaPlayer = MediaPlayer.create(ctx, R.raw.purrs);
            mediaPlayer.start();

            return "";
        }
    }

}
