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

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

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
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.Citrus;
import com.example.citrusclient.R;
import com.example.citrusclient.models.Book;
import com.example.citrusclient.models.BookModel;
import com.example.citrusclient.viewmodels.PublicBooksViewModel;
import com.example.citrusclient.viewmodels.FavoritesViewModel;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;


/**
 * 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<>());
        Citrus citrus = (Citrus)(getActivity().getApplication());
        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)); // アダプターに新しいリストを渡す
            }
        });
        favoritesViewModel.getFavoritesBooksLiveData().observe(getViewLifecycleOwner(), (Observer<? super List<BookModel>>) new Observer<List<BookModel>>() {
            @Override
            public void onChanged(List<BookModel> stringHashSetHashMap) {
                if (stringHashSetHashMap != null) {
                    HashMap<String, HashSet<Integer>> newMap = new HashMap<>();

                    // 変換処理
                    for (BookModel bookModel : stringHashSetHashMap) {
                        if(!newMap.containsKey(bookModel.getAccountId())){
                            newMap.put(bookModel.getAccountId(), new HashSet<>());
                        }
                        newMap.get(bookModel.getAccountId()).add(bookModel.getBookId());
                    }
                    System.out.println("aaaaaaaaa");
                    adapter.updateFavorites(newMap);
                } else {
                    adapter.updateFavorites(new HashMap<>());
                }
            }
        });

//        favoritesViewModel.getFavoritedAccountsLiveData().observe(getViewLifecycleOwner(), new Observer<HashMap<String, Integer>>() {
//            @Override
//            public void onChanged(HashMap<String, Integer> likedBooksCount) {
//                if (likedBooksCount != null) {
//                    adapter.updateFavorited(likedBooksCount); // HashMapを渡す
//                }
//            }
//        });

        // Booksを読み込む
        publicBooksViewModel.loadAllBooks();
        favoritesViewModel.loadFavoritesBooks(citrus.getAccountId(), citrus.getToken());
        //favoritesViewModel.loadFavoritedAccounts(citrus.getCurLookingAccountId(), citrus.getCurLookingBookId(), citrus.getToken());

        // 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);
                favoritesViewModel.loadFavoritesBooks(citrus.getAccountId(), citrus.getToken());
                favoritesViewModel.loadFavoritedAccounts(citrus.getCurLookingAccountId(), citrus.getCurLookingBookId(), citrus.getToken());
                Log.d(TAG, "Search query: " + query);
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
//                adapter.filter(newText); // フィルタリングを実行
                searchWord = newText;
                loadSearchResults(searchWord, sortBy);
                favoritesViewModel.loadFavoritesBooks(citrus.getAccountId(), citrus.getToken());
                favoritesViewModel.loadFavoritedAccounts(citrus.getCurLookingAccountId(), citrus.getCurLookingBookId(), citrus.getToken());
                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(sort != null) sortBy = sort;//ソートはまだ
        Log.d(TAG, "Search query: " + title + accountId);

        if(title != ""|| accountId != "" || sort != null){
//            if(sort != null) {
                publicBooksViewModel.loadSearchBooks(title, accountId, sortBy);//title,accountidでの検索
                System.out.println("title: "+title+" accountId: "+accountId+" sortBy: "+sortBy);
//            }
        }else {
                publicBooksViewModel.loadAllBooks();
            // titleとaccountIdを使って検索
        }
    }
}
/*
155-173にかけてHashMapでやり取りしてたのがList<BookModel>に変わったので,その中にあるaccountIdとbookidを取り出してHashMap(String, HashSet<Integer>)におさめる
 */