package code.abdulrahman.bookStore;

import android.os.Bundle;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentTransaction;

public class MainActivity extends AppCompatActivity implements OnItemSelectedListener {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //( we have three activity_main files in three different folders)
        // Android os detects the device and orientation and
        // determines which one to call
        setContentView(R.layout.activity_main);
        // savedInstanceState is null when onCreate is called for the first time
        if (savedInstanceState == null) {
            BookTitleListFragment firstFragment = new BookTitleListFragment();
            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
            ft.add(R.id.frame1, firstFragment).addToBackStack("bookTitles");
            if (findViewById(R.id.layoutWithDaulFragments) != null) {
                BookTitleAndDescriptionlFragment secondFragment = new BookTitleAndDescriptionlFragment();
                Bundle args = new Bundle();
                args.putInt("position", 0);
                secondFragment.setArguments(args);   // (1) Communicate with Fragment using Bundle
                ft.add(R.id.frame2, secondFragment);     // add    Fragment
            }
            ft.commit();
        }
    }

    @Override
    public void onBookItemSelected(int position) {
        Toast.makeText(this, "Called By Fragment A: position - " + position, Toast.LENGTH_SHORT).show();
        // Load Book Detail Fragment
        BookTitleAndDescriptionlFragment secondFragment = new BookTitleAndDescriptionlFragment();
        Bundle args = new Bundle();
        args.putInt("position", position);
        secondFragment.setArguments(args);
        if (findViewById(R.id.frame2) != null) {
            getSupportFragmentManager()
                    .beginTransaction()
                    .replace(R.id.frame2, secondFragment)
                    .addToBackStack(null)
                    .commit();
        } else {
            getSupportFragmentManager()
                    .beginTransaction()
                    .replace(R.id.frame1, secondFragment)
                    .addToBackStack(null)
                    .commit();
        }
    }
}
