package code.abdulrahman.bookStore;

import android.content.Context;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class BookTitleListFragment extends Fragment {
  ArrayAdapter<String> booksAdapter;
  private OnItemSelectedListener listener;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    booksAdapter = new ArrayAdapter<String>(getContext(),
            android.R.layout.simple_list_item_1, Book.bookList);
  }

  //--OnItemSelectedListener listener;
  // This event fires 1st, before creation of fragment or any views
  // The onAttach method is called when the Fragment instance is associated with an Activity.
  // This does not mean the Activity is fully initialized.
  @Override
  public void onAttach(Context context) {
    super.onAttach(context);
    if(context instanceof OnItemSelectedListener){    // context instanceof YourActivity
      this.listener = (OnItemSelectedListener) context; // = (YourActivity) context
    } else {
      throw new ClassCastException(context.toString()
              + " must implement BookMenuFragment.OnItemSelectedListener");
    }
  }

  @Override
  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup parent, @Nullable Bundle savedInstanceState) {
    // Inflate the xml file for the fragment
    return inflater.inflate(R.layout.fragment_book_title_list, parent, false);
  }

  @Override
  public void onViewCreated(View view, Bundle savedInstanceState) {

    ListView itemsViewList = view.findViewById(R.id.listViewItems);
    itemsViewList.setAdapter(booksAdapter);

    itemsViewList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
      @Override
      public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        // go to activity to load book details fragment
        listener.onBookItemSelected(position); // (3) Communicate with Activity using Listener
      }
    });
  }
}
