Newer
Older
CitrusClient / app / src / main / java / com / example / citrusclient / views / SearchFragment.java
package com.example.citrusclient.views;

import android.annotation.SuppressLint;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.SearchView;
import android.widget.Spinner;

import com.example.citrusclient.R;
import com.example.citrusclient.viewmodels.PublicBooksViewModel;
import com.example.citrusclient.viewmodels.FavoritesViewModel;

import java.util.ArrayList;




/**
 * A simple {@link Fragment} subclass.
 * Use the {@link SearchFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class SearchFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public SearchFragment() {
        // Required empty public constructor
    }

    private static final String TAG = SearchFragment.class.getSimpleName();
    private final SearchFragment self = this;

    private SearchView searchView;
    private String searchWord="";
    private MyAdapter adapter;
    private RecyclerView recyclerView;
    private RecyclerView recyclerView1; // sort_by用のRecyclerView
    private PublicBooksViewModel publicBooksViewModel;
    private FavoritesViewModel favoritesViewModel;

    private Integer sortBy = 0;

    EditText editText;

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment SearchFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static SearchFragment newInstance(String param1, String param2) {
        SearchFragment fragment = new SearchFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    private ArrayList publicList;
    private ArrayList name;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }

        publicBooksViewModel = new ViewModelProvider(this).get(PublicBooksViewModel.class);
        favoritesViewModel = new ViewModelProvider(this).get(FavoritesViewModel.class);
    }

//    @Override
//    public View onCreateView(LayoutInflater inflater, ViewGroup container,
//                             Bundle savedInstanceState) {
//        // Inflate the layout for this fragment
//        return inflater.inflate(R.layout.fragment_search, container, false);
//    }
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // フラグメントのレイアウトをインフレート
    return inflater.inflate(R.layout.fragment_search, container, false);
    }
    @SuppressLint("WrongViewCast")
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        adapter = new MyAdapter(new ArrayList<>());
        RecyclerView recyclerView = view.findViewById(R.id.public_list);
        recyclerView.setLayoutManager(new LinearLayoutManager(view.getContext()));
        recyclerView.setAdapter(adapter);

        // Spinnerの設定
        Spinner sortBySpinner = view.findViewById(R.id.sort_by_spinner);
        ArrayAdapter<CharSequence> spinnerAdapter = ArrayAdapter.createFromResource(
                getContext(),
                R.array.sort_options, // res/values/strings.xmlで定義
                android.R.layout.simple_spinner_item);
        spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        sortBySpinner.setAdapter(spinnerAdapter);

        // Spinnerの選択リスナーを設定
        sortBySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                // positionに基づいてソートの処理を行う
                sortBy = position; // 例えば、0が"Sort by Title"、1が"Sort by Author"など
                System.out.println(position);
                loadSearchResults(searchWord, sortBy);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // 何も選択されていない場合の処理(必要に応じて)
                loadSearchResults(searchWord, sortBy);
            }
        });

        // データの取得とアダプターへのセット
        publicBooksViewModel.getAllBooksLiveData().observe(getViewLifecycleOwner(), books -> {
            if (books != null) {
                adapter.setBooks(new ArrayList<>(books)); // アダプターに新しいリストを渡す
            }
        });

        // Booksを読み込む
        publicBooksViewModel.loadAllBooks();

        // SearchViewの設定
        SearchView searchView = view.findViewById(R.id.search_word);
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                searchWord = query;
                loadSearchResults(searchWord, sortBy);
                Log.d(TAG, "Search query: " + query);
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
//                adapter.filter(newText); // フィルタリングを実行
                searchWord = newText;
                loadSearchResults(searchWord, sortBy);
                Log.d(TAG, "Search query: " + newText);
                return true;
            }
        });
    }

    private void loadSearchResults(String query, Integer sort) {
        String title = "", accountId = "";
        if(query != null) {
            // 空白で分割
            String[] parts = query.split(" ");
            title = parts.length > 0 ? parts[0] : ""; // 最初の部分をtitleに
            accountId = parts.length > 1 ? parts[1] : ""; // 2番目の部分をaccountIdに
        }
        if(sortBy != null) sortBy = sort;//ソートはまだ
        Log.d(TAG, "Search query: " + title + accountId);

        if(title != ""|| accountId != ""){
            if(sort != null) {
                publicBooksViewModel.loadSearchBooks(title, accountId, sortBy);//title,accountidでの検索
                System.out.println("title: "+title+" accountId: "+accountId+" sortBy: "+sortBy);
            }
        }else {
                publicBooksViewModel.loadAllBooks();
            // titleとaccountIdを使って検索
        }
    }
}