package ch.threema.app.voip.activities;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.widget.Toast;

import org.koin.java.KoinJavaComponent;
import org.slf4j.Logger;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import ch.threema.app.R;
import ch.threema.app.activities.ThreemaActivity;
import ch.threema.app.di.DependencyContainer;
import ch.threema.app.utils.ConfigUtils;
import ch.threema.app.utils.ContactLookupUtil;
import ch.threema.app.voip.util.VoipUtil;
import static ch.threema.base.utils.LoggingKt.getThreemaLogger;
import ch.threema.storage.models.ContactModel;

import static ch.threema.app.startup.AppStartupUtilKt.finishAndRestartLaterIfNotReady;
import static ch.threema.app.utils.ActiveScreenLoggerKt.logScreenVisibility;

/**
 * Handle call action intents (sent by calling someone through the Android phonebook),
 * start the call activity.
 */
public class CallActionIntentActivity extends ThreemaActivity {
    private static final Logger logger = getThreemaLogger("CallActionIntentActivity");

    @NonNull
    private final DependencyContainer dependencies = KoinJavaComponent.get(DependencyContainer.class);

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        logScreenVisibility(this, logger);
        if (finishAndRestartLaterIfNotReady(this)) {
            return;
        }

        if (!ConfigUtils.isCallsEnabled() || !dependencies.getLicenseService().isLicensed()) {
            Toast.makeText(getApplicationContext(), R.string.voip_disabled, Toast.LENGTH_LONG).show();
            this.finish();
            return;
        }

        ContactModel contact = null;

        // Validate intent
        final Intent intent = getIntent();
        if (Intent.ACTION_VIEW.equals(intent.getAction())) {
            if (getString(R.string.call_mime_type).equals(intent.getType())) {
                Uri uri = intent.getData();
                if (uri != null && ContentResolver.SCHEME_CONTENT.equalsIgnoreCase(uri.getScheme())) {
                    try (Cursor cursor = getContentResolver().query(uri, null, null, null, null)) {
                        if (cursor != null && cursor.moveToNext()) {
                            String contactIdentity = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.RawContacts.Data.DATA1));
                            contact = dependencies.getContactService().getByIdentity(contactIdentity);
                        }
                    } catch (SecurityException e) {
                        logger.error("SecurityException", e);
                    }
                }
            }
        } else if (Intent.ACTION_CALL.equals(intent.getAction())) {
            final Uri uri = intent.getData();
            if (uri != null && "tel".equals(uri.getScheme())) {
                // Look up contact identity
                contact = ContactLookupUtil.phoneNumberToContact(this, dependencies.getContactService(), uri.getSchemeSpecificPart());
            }
        }

        if (contact == null) {
            Toast.makeText(this, R.string.voip_contact_not_found, Toast.LENGTH_LONG).show();
            logger.warn("Invalid call intent: Contact not found");
            finish();
            return;
        }

        logger.info("Calling {} via call intent action", contact.getIdentity());

        if (!VoipUtil.initiateCall(this, contact, false, this::finish)) {
            finish();
        }
    }
}
