package jp.gihyo.mitoma.android.s010901basictrans;

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;

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 jp.gihyo.mitoma.android.s010901basictrans.extra.Activity_B;

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());
        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){
            // Activity_Bへ遷移
            String message = etValue.getText().toString();
            Intent intent = new Intent(getApplicationContext(), Activity_B.class);
            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 data = result.getData();
                Log.i(TAG,"A Infoテスト");
                Log.d(TAG,"A Debugテスト");
                if (data != null) {
                    String message = data.getStringExtra("message");
                    etValue.setText(message);
                }
            }
        }
    }
}
