package jp.gihyo.mitoma.android.s2202intentstep01;

import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;

public class Activity_A extends AppCompatActivity {
    EditText etValue;
    private ActivityResultLauncher<Intent> launcher;
    private static final String TAG = "Activity_A";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_a);
        this.launcher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                new MyActivityResultCallback());
        //Log.i(TAG,"onCreateスタート");
        etValue = findViewById(R.id.etValue);
        Button button = findViewById(R.id.button);
        button.setOnClickListener(new ButtonClick());
    }
    private class ButtonClick implements View.OnClickListener{
        public void onClick(View view){
            String message = etValue.getText().toString();
            // 暗黙的インテントでS2201のActivity_Bへ遷移
            Intent intent = new Intent();
            intent.setAction("jp.gihyo.mitoma.android.implicit_test.ACTION_SUB");
            intent.putExtra("message",message);
            launcher.launch(intent);
        }
    }
    private class MyActivityResultCallback implements ActivityResultCallback<ActivityResult> {
        @Override
        public void onActivityResult(ActivityResult result) {
            if (result.getResultCode() == RESULT_OK) {
                Intent intent = result.getData();
                if (intent != null) {
                    String message = intent.getStringExtra("message");
                    etValue.setText(message);
                }else{
                    Toast.makeText(Activity_A.this,"戻り値無し",Toast.LENGTH_LONG).show();
                }
            }
        }
    }
}
