package com.app.simplitend.callwhitelisting;

import static com.app.simplitend.callwhitelisting.CallUnBlockingWorker.CALL_BLOCKING_WORk;

import android.os.Build;
import android.telecom.Call;
import android.telecom.CallScreeningService;
import android.util.Log;

import androidx.work.OneTimeWorkRequest;
import androidx.work.WorkManager;
import androidx.work.WorkRequest;

import com.app.simplitend.apputils.AppUtil;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber;

import java.util.Set;
import java.util.concurrent.TimeUnit;

public class CallService extends CallScreeningService {

    public static final String CONTACT_WHITE_LISTING_TAG = "CONTACT_WHITELISTING";
    public static final long CALL_UNBLOCKING_INTERVAL = 30;

    private static void endCall(CallResponse.Builder builder) {
        builder.setDisallowCall(true)
                .setRejectCall(true)
                .setSkipNotification(true);
    }

    @Override
    public void onScreenCall(Call.Details callDetails) {

        if ("911".equals(callDetails.getHandle().getSchemeSpecificPart())){
            Log.d(CALL_BLOCKING_WORk, "CALLED 911");
            WorkManager.getInstance(this).cancelAllWorkByTag(CALL_BLOCKING_WORk);
            WorkRequest workRequest = new OneTimeWorkRequest.Builder(CallUnBlockingWorker.class)
                    .setInitialDelay(CALL_UNBLOCKING_INTERVAL, TimeUnit.MINUTES)
                    .addTag(CALL_BLOCKING_WORk)
                    .build();

            WorkManager.getInstance(this).enqueue(workRequest);

            AppUtil.setIsCallBlockingEnabled(this, false);
            Log.d(CALL_BLOCKING_WORk, "CALL BLOCKING DISABLED");
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q &&
                callDetails.getCallDirection() != Call.Details.DIRECTION_INCOMING) {
            return;
        }

        CallResponse.Builder builder = new CallResponse.Builder();
        try {
            String phoneNumber = callDetails.getHandle().getSchemeSpecificPart();
            Log.d(CONTACT_WHITE_LISTING_TAG, "CALL FROM -> " + phoneNumber);

            if (!AppUtil.isCallBlockingEnabled(this)){
                // senior has deactivated the call blocking feature
                throw new Exception("SENIOR HAS DEACTIVATED CALL BLOCKING");
            }

            try {
                Phonenumber.PhoneNumber parsed_phone = PhoneNumberUtil.getInstance().parse(phoneNumber, "US");
                phoneNumber = "+" + parsed_phone.getCountryCode() + parsed_phone.getNationalNumber();
            } catch (Exception e) {
                // do nothing
            }

            Log.d(CONTACT_WHITE_LISTING_TAG, "AFTER FORMATTING PHONE NUMBER -> " + phoneNumber);

            Set<String> white_contacts = AppUtil.getWhiteListedContacts(this);
            Log.d(CONTACT_WHITE_LISTING_TAG, "WHITE LISTED CONTACTS -> " + white_contacts);

            if (AppUtil.isUserSubscribed(this) && white_contacts != null && !white_contacts.contains(phoneNumber)){
                endCall(builder);
                Log.d(CONTACT_WHITE_LISTING_TAG, "CALL ENDED");
            }

        } catch (Throwable t) {
            Log.w(CONTACT_WHITE_LISTING_TAG, t);
        } finally {
            respondToCall(callDetails, builder.build());
        }
    }

}