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.content.Context;
import android.graphics.Color;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.core.view.MenuItemCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.text.Editable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.SearchView;
import android.widget.TextView;

import com.example.citrusclient.Citrus;
import com.example.citrusclient.R;
import com.example.citrusclient.models.Book;
import com.example.citrusclient.viewmodels.PublicBooksViewModel;

import java.util.ArrayList;
import java.util.Calendar;
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 int sortBy = 0;

    EditText editText;

    private MyAdapter adapter;

    /**
     * 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;
    PublicBooksViewModel publicBooksViewModel;

    @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);
    }

    @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);
    }

    @SuppressLint("WrongViewCast")
    public void onViewCreated(@NonNull View view, @NonNull Bundle saveInstanceState){
        super.onViewCreated(view, saveInstanceState);

//        publicList = new ArrayList<>();
//        name = new ArrayList<>();
//
//        RecyclerView recyclerView = view.findViewById(R.id.public_list);
//        recyclerView.setHasFixedSize(true);
//        recyclerView.setLayoutManager(new LinearLayoutManager(view.getContext()));
//        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(view.getContext());
//        recyclerView.setLayoutManager(layoutManager);
//        PublicAdapter publicAdapter = new PublicAdapter(name, publicList, getActivity());
//        recyclerView.setAdapter(publicAdapter);
//        publicBooksViewModel.getAllBooksLiveData().observe(getViewLifecycleOwner(), new Observer<ArrayList<Book>>() {
//            @Override
//            public void onChanged(ArrayList<Book> books) {
//                if (books != null) {
//                    for (Book book : books) {
//                        name.add(book.getAccountId());
//                    }
//                    publicList = new ArrayList<>(books);
//                } else {
//                    publicList = new ArrayList<>();
//                }
//                adapter = new MyAdapter(publicList); // アダプターを更新
//                recyclerView.setAdapter(adapter); // アダプターを再設定
//                adapter.notifyDataSetChanged(); // アダプターに変更を通知
//                System.out.println(name);
//                adapter = new MyAdapter(publicList);
//                recyclerView.setAdapter(adapter);
//                recyclerView.setLayoutManager(new LinearLayoutManager(view.getContext()));
//            }
//        });
//        publicBooksViewModel.loadAllBooks();
//
//        SearchView searchView = view.findViewById(R.id.search_word);
//        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
//            @Override
//            public boolean onQueryTextSubmit(String query) {
//                loadSearchResults(query);
//                return false;
//            }
//
//            @Override
//            public boolean onQueryTextChange(String newText) {
//                adapter.filter(newText);
//                return true;
//            }
//        });

        adapter = new MyAdapter(new ArrayList<>());
        RecyclerView recyclerView = view.findViewById(R.id.public_list);
        recyclerView.setLayoutManager(new LinearLayoutManager(view.getContext()));
        recyclerView.setAdapter(adapter);

        publicBooksViewModel.getAllBooksLiveData().observe(getViewLifecycleOwner(), new Observer<ArrayList<Book>>() {
            @Override
            public void onChanged(ArrayList<Book> books) {
                if (books != null) {
                    publicList = new ArrayList<>(books);
                    adapter.setBooks(publicList); // アダプターに新しいリストを渡す
                }
            }
        });

        publicBooksViewModel.loadAllBooks();

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

            @Override
            public boolean onQueryTextChange(String newText) {
                //adapter.filter(newText); // フィルタリングを実行
                loadSearchResults(newText);
                System.out.println("aho");
                return true;
            }
        });
    }

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

        if(title != null){
            if(accountId != null){
                publicBooksViewModel.loadSearchBooks(title, accountId, sortBy);//title,accountidでの検索
            }else publicBooksViewModel.loadSearchTitleBooks(title, sortBy);//titleのみの検索
            if(accountId != null){
                publicBooksViewModel.loadSearchAccountIdBooks(accountId, sortBy);//accountidでの検索
            }else publicBooksViewModel.loadAllBooks();
            // titleとaccountIdを使って検索
    }
}

class PublicAdapter extends RecyclerView.Adapter<PublicAdapter.PublicViewHolder>{

    private List<Book> publicList;
    private List accountIdList;
    private Context context;

    PublicAdapter(List id, List<Book> publics, Context context){
        this.accountIdList = id;
        this.publicList = publics;
        this.context = context;
    }

    public void setBooks(List<Book> publics){
        publicList = publics;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public PublicViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.a_public_book, parent, false);
        return new PublicViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull PublicAdapter.PublicViewHolder holder, int position) {
            holder.idText.setText(accountIdList.get(position).toString());
            holder.idText.setHeight(30);
            holder.idText.setWidth(100);
            Book publicData = this.publicList.get(position);
            holder.publicButton.setText(publicData.getTitle());
            int red;
            int green;
            int blue;
            if (publicData.getColor() == null) {
                red = 255;
                green = 255;
                blue = 255;
            } else if (publicData.getColor().length() < 7) {
                red = 255;
                green = 255;
                blue = 255;
            } else {
                red = Integer.parseInt(publicData.getColor().substring(1, 3), 16);
                green = Integer.parseInt(publicData.getColor().substring(3, 5), 16);
                blue = Integer.parseInt(publicData.getColor().substring(5, 7), 16);
            }

            holder.publicButton.setBackgroundColor(Color.rgb(red, green, blue));
            holder.publicButton.setTextColor(Color.rgb(255 - red, 255 - green, 255 - blue));
//            holder.publicButton.setOnClickListener(v -> {
//                Calendar c = Calendar.getInstance();
//                Activity activity = (Activity) context;
//                Citrus citrus = (Citrus) activity.getApplication();
//                citrus.setCurYear(c.get(Calendar.YEAR));
//                citrus.setCurMonth(c.get(Calendar.MONTH) + 1);
//                citrus.setCurDay(c.get(Calendar.DATE));
//                citrus.setCurBookId(publicData.getBookId());
//                ((MainActivity) activity).showFragment(new HomeFragment());
//            });
    }

    @Override
    public int getItemCount() {
        return publicList.size();
    }

    static class PublicViewHolder extends RecyclerView.ViewHolder{
        Button publicButton;
        TextView idText;
        public PublicViewHolder(@NonNull View itemView){

            super(itemView);
            publicButton = itemView.findViewById(R.id.public_button);
            idText = itemView.findViewById(R.id.public_id);
        }
    }
}