package com.zoblak.farm;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.IBinder;

/**
 * Created by senadu on 11/18/16.
 */

public class SoundPlayingService extends Service
{
    private Ringtone ringtone;

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

    @Override
    public int onStartCommand(Intent intent, int flags, int startId)
    {
        startTheAlarm();

        return START_NOT_STICKY;
    }

    @Override
    public void onDestroy()
    {
        stopTheAlarm();
    }

    public static void startPlayingAlarm(Context context) {
        Intent startIntent = new Intent(context, SoundPlayingService.class);
        context.startService(startIntent);
    }

    public static void stopPlayingAlarm(Context context) {
        Intent startIntent = new Intent(context, SoundPlayingService.class);
        context.stopService(startIntent);
    }

    @SuppressWarnings("deprecation")
    private void startTheAlarm() {
        Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
        ringtone = RingtoneManager.getRingtone(this, notification);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            AudioAttributes attributes = new AudioAttributes.Builder()
                    .setUsage(AudioAttributes.USAGE_GAME)
                    .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                    .build();
            ringtone.setAudioAttributes(attributes);
        } else {
            ringtone.setStreamType(AudioManager.STREAM_ALARM);
        }
        ringtone.play();
    }

    public void stopTheAlarm() {
        if(ringtone != null && ringtone.isPlaying()) {
            ringtone.stop();
        }
    }
}