/*
 * Copyright (C) 2025 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.snippet.telecom;

import static android.Manifest.permission.READ_PHONE_NUMBERS;
import static android.Manifest.permission.READ_PHONE_STATE;

import android.content.Context;
import android.os.Build;
import android.telephony.SubscriptionInfo;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;
import androidx.annotation.RequiresPermission;
import androidx.test.platform.app.InstrumentationRegistry;
import com.google.android.mobly.snippet.Snippet;
import com.google.android.mobly.snippet.rpc.Rpc;
import com.google.android.mobly.snippet.rpc.RpcDefault;

/** Snippet class for TelephonyManager APIs. */
public class TelephonyManagerSnippet implements Snippet {

  private final Context context;
  private final SubscriptionManager subscriptionManager;
  private final TelephonyManager telephonyManager;

  public TelephonyManagerSnippet() {
    context = InstrumentationRegistry.getInstrumentation().getContext();
    subscriptionManager = context.getSystemService(SubscriptionManager.class);
    telephonyManager = context.getSystemService(TelephonyManager.class);
  }

  @RequiresPermission(allOf = {READ_PHONE_NUMBERS, READ_PHONE_STATE})
  @Rpc(
      description =
          "Gets the line 1 phone number, or optionally get phone number for the "
              + "simSlot (slot# start from 0, only valid for API level > 32)")
  public String telephonyGetPhoneNumber(@RpcDefault("0") Integer simSlot) {
    String phoneNumber = "";

    if (Build.VERSION.SDK_INT < 33) {
      phoneNumber = telephonyManager.getLine1Number();
    } else {
      SubscriptionInfo subscriptionInfo =
          subscriptionManager.getActiveSubscriptionInfoForSimSlotIndex(simSlot.intValue());
      if (subscriptionInfo != null) {
        phoneNumber = subscriptionManager.getPhoneNumber(subscriptionInfo.getSubscriptionId());
      }
    }

    return phoneNumber;
  }
}

