package com.example.dialer;

import android.os.Bundle;
import android.net.Uri;
import android.content.Context;
import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
import io.flutter.plugin.common.MethodCall;
import android.telecom.TelecomManager;
import android.telecom.PhoneAccountHandle;
import java.util.List;
import java.util.Collections;

public class MainActivity extends FlutterActivity {
    private static final String CHANNEL = "call_service";

    @Override
    public void configureFlutterEngine(FlutterEngine flutterEngine) {
        super.configureFlutterEngine(flutterEngine);
        new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANNEL)
            .setMethodCallHandler(
                new MethodCallHandler() {
                    @Override
                    public void onMethodCall(MethodCall call, Result result) {
                        if (call.method.equals("makeGsmCall")) {
                            String phoneNumber = call.argument("phoneNumber");
                            int simSlot = call.argument("simSlot");
                            TelecomManager telecomManager = (TelecomManager) getSystemService(Context.TELECOM_SERVICE);
                            List<PhoneAccountHandle> accounts = telecomManager.getCallCapablePhoneAccounts();
                            PhoneAccountHandle selectedAccount = accounts.get(simSlot < accounts.size() ? simSlot : 0);
                            Bundle extras = new Bundle();
                            extras.putParcelable(TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE, selectedAccount);
                            Uri uri = Uri.fromParts("tel", phoneNumber, null);
                            telecomManager.placeCall(uri, extras);
                            result.success(Collections.singletonMap("status", "calling"));
                        } else if (call.method.equals("hangUpCall")) {
                            // TODO: implement hangUpCall if needed
                            result.success(Collections.singletonMap("status", "ended"));
                        } else {
                            result.notImplemented();
                        }
                    }
                }
            );
    }
}