package lenka.example.com.testtask.services;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

import java.io.File;

import lenka.example.com.testtask.DataBaseHelper;
import lenka.example.com.testtask.activities.cameraActivity.CustomCameraActivity;

/**
 * Created by Lenka on 09.04.2016.
 */
public class AlarmReceiver extends BroadcastReceiver {

    public AlarmReceiver() {
        super();
    }

    @Override
    public void onReceive(Context context, Intent intent) {

        deleteOlderFile(context);
    }

    private void deleteOlderFile(Context context){
        File file = new File(context.getApplicationContext().getFilesDir(), CustomCameraActivity.PHOTOS_DIRECTORY_NAME);
        File[] files = file.listFiles();
        if (files.length == 0)
            selfCancel(context);
        else{
            DataBaseHelper db = new DataBaseHelper(context);
            db.addNote(files[0].getName() + " удален");
            Toast.makeText(context, files[0].getName() + " удален", Toast.LENGTH_SHORT).show();
            files[0].delete();
        }
    }

    private void selfCancel(Context context){
        Intent alarmIntent = new Intent(context, AlarmReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, 0);
        AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        manager.cancel(pendingIntent);
        pendingIntent.cancel();

        Toast.makeText(context, "Service Stopped", Toast.LENGTH_SHORT).show();
    }
}
