package tech.starwin.service.sms;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.provider.Telephony;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.FragmentActivity;
import android.widget.Toast;

import tech.starwin.LibConfig;
import tech.starwin.utils.PreferencesManager;
import tech.starwin.utils.context_utils.EasyActivityResult;
import tech.starwin.utils.context_utils.PermissionsHelper;
import tech.starwin.utils.ui_utils.UIHelper;

/**
 * Created by SiKang on 2018/11/5.
 */
public class SmsActivity extends FragmentActivity {
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        Toast.makeText(this, "please try again", Toast.LENGTH_SHORT).show();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //获取被替换之前的默认应用
            String defaultPkg = PreferencesManager.get().getDefaultSmsPackage();
            //恢复默认应用
            Intent defaultIntent = new Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);
            defaultIntent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, defaultPkg);
            new EasyActivityResult(this).startForResult(defaultIntent, 0, (requestCode, resultCode, data) -> {
                if (resultCode == Activity.RESULT_OK) {
                    getPackageManager().clearPackagePreferredActivities(LibConfig.APPLICATION_ID);
                    Intent intent = new Intent(getIntent().getAction(), getIntent().getData());
                    intent.putExtras(getIntent().getExtras());
                    intent.setPackage(defaultPkg);
                    startActivity(intent);
                }
                finish();
            });
        } else {
            UIHelper.showToast(this, "please try again!");
            finish();
        }
    }
}
