package com.app.simplitend.patient_dashboard.foodreminders;

import static com.app.simplitend.patient_dashboard.foodreminders.FoodReminderYesReceiver.WHICH_FOOD_REMINDER;
import static com.app.simplitend.patient_dashboard.foodreminders.FoodScheduler.FOOD_REMINDER_NOTIFICATION_ID;

import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;

import com.app.simplitend.apputils.AppUtil;
import com.app.simplitend.apputils.RetrofitHelper;
import com.app.simplitend.welcome.welcomepatient.mvvm.models.CallResponse;

import java.util.HashMap;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.http.Body;
import retrofit2.http.Header;
import retrofit2.http.POST;

public class FoodReminderNotifyingService extends Service {

    private static final String TAG = "FoodScheduler";

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

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        int which_meal = intent.getIntExtra(WHICH_FOOD_REMINDER, -1);

        if (which_meal != -1){
            Log.d(TAG, "NO clicked for " + which_meal);
            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.cancel(FOOD_REMINDER_NOTIFICATION_ID + which_meal);

            NotificationsApiService apiService = RetrofitHelper.getRetrofit().create(NotificationsApiService.class);

            Map<String, Integer> body = new HashMap<>();
            body.put("patient_id", AppUtil.getPatientUid(this));
            body.put("meal_type", which_meal);

            apiService.sendMealNotification("Bearer " + AppUtil.getPatientToken(this), body)
                    .enqueue(new Callback<CallResponse<Object>>() {
                        @Override
                        public void onResponse(Call<CallResponse<Object>> call, Response<CallResponse<Object>> response) {
                            Log.d(TAG, "onResponse: " + response);
                        }

                        @Override
                        public void onFailure(Call<CallResponse<Object>> call, Throwable t) {
                            Log.d(TAG, "onFailure: " + t);
                        }
                    });

        }
        return super.onStartCommand(intent, flags, startId);
    }

    public interface NotificationsApiService{

        @POST("api/send-notification-to-caregiver-meals-time")
        Call<CallResponse<Object>> sendMealNotification(@Header("Authorization") String token, @Body Map<String, Integer> body);
    }
}
