package com.kbs.kbsintranett;

import android.content.Context;
import androidx.annotation.NonNull;
import androidx.work.Worker;
import androidx.work.WorkerParameters;
import java.util.List;

public class TaskReminderWorker extends Worker {

    public TaskReminderWorker(@NonNull Context context, @NonNull WorkerParameters params) {
        super(context, params);
    }

    @NonNull
    @Override
    public Result doWork() {
        Context context = getApplicationContext();
        List<TaskItem> tasks = CacheManager.getTasks(context);
        String myEmail = UserManager.getInstance().getUserEmail();
        long now = System.currentTimeMillis();

        for (TaskItem task : tasks) {
            if (!task.isNotificationsEnabled() || task.isFullyCompleted() || task.getParticipantStatus(myEmail)) continue;

            long diff = task.getDueDate() - now;

            // Varsle hvis fristen er i dag (innenfor 24 timer)
            if (diff > 0 && diff < 86400000L) {
                NotificationHelper.showNotification(context, "Frist i dag!", "Oppgaven '" + task.getTitle() + "' forfaller snart.");
            }
            // Varsle hvis over frist (hver gang worker kjører, f.eks annenhver dag)
            else if (diff < 0) {
                NotificationHelper.showNotification(context, "Over frist!", "Oppgaven '" + task.getTitle() + "' er forsinket.");
            }
        }
        return Result.success();
    }
}