package com.app.simplitend.callwhitelisting;

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

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

import java.util.Set;

public class CallService extends CallScreeningService {

    public static final String CONTACT_WHITE_LISTING_TAG = "CONTACT_WHITELISTING";

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

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

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

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

}