package com.revoapp.calendar.service;

import android.app.AlarmManager;
import android.app.IntentService;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

import com.revoapp.api.database.calendar.pojo.Events;
import com.revoapp.api.logger.RevoLogger;
import com.revoapp.api.utils.DateTimeConvert;
import com.revoapp.calendar.database.DatabaseHandler;
import com.revoapp.calendar.database.PreferencesManager;

import java.util.ArrayList;
import java.util.Calendar;

public class EventAlarmServices extends IntentService {
    private static final String TAG = "CalendarEventAS";

    public static final String CREATE = "CREATE";

    private IntentFilter matcher;

    public EventAlarmServices() {
        super("EventAlarmServices");

        matcher = new IntentFilter();
        matcher.addAction(CREATE);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        String action = intent.getAction();
        if (matcher.matchAction(action)) {
            execute(action);
        }
    }

    private void execute(String action) {
        RevoLogger.log(RevoLogger.VERBOSE, this.getClass().getName(),
                "execute", "action = " + action);

        DatabaseHandler db = new DatabaseHandler(this);
        ArrayList<Events> eventsList = db.getAllEvents();

        AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

        int prevAlarmsCount = PreferencesManager.getEventAlarmCount(this);

        RevoLogger.log(RevoLogger.DEBUG, this.getClass().getName(),
                "execute", "canceling alarm for: " + prevAlarmsCount + " event(s)");

        for (int i = 0; i < prevAlarmsCount; i++) {
            Intent intent = new Intent("com.revoapp.notification.EVENTS");
            PendingIntent pendingIntent = PendingIntent.getBroadcast(this, i, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            pendingIntent.cancel();
            am.cancel(pendingIntent);
        }

        int requestCode = 0;

        for (Events event : eventsList) {
            long time = event.getDate() * 1000;

            Intent i = new Intent("com.revoapp.notification.EVENTS");
            i.putExtra("id", event.getId());
            PendingIntent pendingIntent = PendingIntent.getBroadcast(this, requestCode, i, PendingIntent.FLAG_UPDATE_CURRENT);

            requestCode++;

            if (checkTime(time)) {
                am.set(AlarmManager.RTC_WAKEUP, time, pendingIntent);
                RevoLogger.log(RevoLogger.DEBUG, this.getClass().getName(),
                        "execute", "Alarm set at:" + DateTimeConvert.getDateTime(this, time / 1000) +
                                " for:" + event.toString());
            } else {
                pendingIntent.cancel();
                RevoLogger.log(RevoLogger.DEBUG, this.getClass().getName(),
                        "execute", "Alarm NOT set at:" + DateTimeConvert.getDateTime(this, time / 1000) +
                                " for:" + event.toString());
            }
        }

        PreferencesManager.setEventAlarmCount(this, requestCode);

        RevoLogger.log(RevoLogger.DEBUG, this.getClass().getName(),
                "execute", "Alarm set for:" + requestCode + " event(s)");
    }

    private boolean checkTime(long time) {
        //TODO check
        Calendar now = Calendar.getInstance();
        long nowMillis = now.getTimeInMillis();
        return time > nowMillis;
    }
}