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 android.os.Bundle;

import com.revoapp.api.Config;
import com.revoapp.api.database.calendar.pojo.Pills;
import com.revoapp.api.helper.BroadcastHelper;
import com.revoapp.api.logger.RevoLogger;
import com.revoapp.api.utils.DateTimeConvert;
import com.revoapp.calendar.components.MultiMap;
import com.revoapp.calendar.database.PillsDatabaseHandler;
import com.revoapp.calendar.database.PreferencesManager;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

public class PillsAlarmServices extends IntentService {
    public static final String CREATE = "CREATE";

    private IntentFilter matcher;

    public PillsAlarmServices() {
        super("PillsAlarmServices");

        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);

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

        long prevAlarmsCount = PreferencesManager.getPillsAlarmCount(this);
        for (int i = 0; i < prevAlarmsCount; i++) {
            Intent intent = BroadcastHelper.getIntent(BroadcastHelper.ACTION_PILLS);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(this, i, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            pendingIntent.cancel();
            am.cancel(pendingIntent);
        }

        PillsDatabaseHandler db = new PillsDatabaseHandler(this);
        ArrayList<Pills> pillsList = db.getAllPills(true);

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

        //sprawdzenie czy czas wziecia tabletki nie minal, i zgrupowanie tabletek z tej samej daty
        MultiMap<Long, Integer> map = new MultiMap<Long, Integer>();
        for (Pills pill : pillsList) {
            if (pill.getmDateTime() != 0) {
                if (pill.getmDateTime() * 1000 > (new Date().getTime() - Config.PILL_EXPIRATION_TIME)) {
                    map.add(pill.getmDateTime() * 1000, pill.getmId());
                } else {
                    db.expirePill(pill.getmId());
                }
            } else {
                db.deletePill(pill.getmId());
            }
        }

        int requestCode = 0;
        Iterator iterator = map.keySet().iterator();
        while (iterator.hasNext()) {
            long pillsDate = (Long) iterator.next(); //key
            List<Integer> pillsIdsList = map.get(pillsDate); //value

            RevoLogger.log(RevoLogger.VERBOSE, this.getClass().getName(),
                    "execute", "pillsIdsList size:" + pillsIdsList.size());

            Bundle b = new Bundle();
            b.putIntegerArrayList("id", (ArrayList<Integer>) pillsIdsList);

            Intent i = BroadcastHelper.getIntent(BroadcastHelper.ACTION_PILLS);
            i.putExtra("idBundle", b);
            i.putExtra("pill_date", pillsDate);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(this, requestCode, i, PendingIntent.FLAG_UPDATE_CURRENT);

            requestCode++;

            am.set(AlarmManager.RTC_WAKEUP, pillsDate, pendingIntent);

            RevoLogger.log(RevoLogger.DEBUG, this.getClass().getName(),
                    "execute", "Alarm set at:" + DateTimeConvert.getDateTime(this, pillsDate / 1000));
        }

        PreferencesManager.setPillsAlarmCount(this, requestCode);

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