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

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 android.text.Editable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.NumberPicker;
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.Todo;
import com.example.citrusclient.viewmodels.BooksViewModel;
import com.example.citrusclient.viewmodels.ScheduleViewModel;
import com.example.citrusclient.viewmodels.TodosViewModel;
import com.google.android.material.snackbar.Snackbar;

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

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

    private TodosViewModel todosViewModel;
    private BooksViewModel booksViewModel;


    // 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;

    List<String> bookTitles;

    private Citrus citrus;
    private String accountId;
    private String token;
    private int selectBookNum;

    //編集用
    private boolean isEdit;
    private Todo editTodo;
    private Book editBook;
    private int viwYear;
    private int viwMonth;
    private int viwDay;
    private String viwTitle;

    //追加用コンストラクタ
    public CreateTodoFragment(int viwYear, int viwMonth, int viwDay) {
        this.isEdit = false;
        this.viwYear = viwYear;
        this.viwMonth = viwMonth;
        this.viwDay = viwDay;
        this.viwTitle = "";
    }

    //編集用コンストラクタ
    public CreateTodoFragment(Todo editTodo,Book editBook) {
        this.editTodo = editTodo;
        this.editBook = editBook;
        this.isEdit = true;
        this.viwYear = editTodo.getYear();
        this.viwMonth = editTodo.getMonth();
        this.viwDay = editTodo.getDay();
        this.viwTitle = editTodo.getTitle();

    }

    // TODO: Rename and change types and number of parameters
    public static CreateTodoFragment newInstance(String param1, String param2) {
        CreateTodoFragment fragment = new CreateTodoFragment(0,0,0);
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;

    }

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

        citrus = (Citrus)(getActivity().getApplication());
        accountId = citrus.getAccountId();
        token = citrus.getToken();
        todosViewModel = new ViewModelProvider(this).get(TodosViewModel.class);
        booksViewModel = new ViewModelProvider(this).get(BooksViewModel.class);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_create_todo, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        selectBookNum = 0;

        EditText titleField = view.findViewById(R.id.todo_title_inputField);
        titleField.setText(viwTitle); // 年の初期値を設定

        NumberPicker numberPickerYear = view.findViewById(R.id.numberPickerYear);
        numberPickerYear.setMinValue(citrus.getCurYear());
        numberPickerYear.setMaxValue(citrus.getCurYear() + 30);
        numberPickerYear.setValue(viwYear); // 年の初期値を設定

        NumberPicker numberPickerMonth = view.findViewById(R.id.numberPickerMonth);
        numberPickerMonth.setMinValue(1);
        numberPickerMonth.setMaxValue(12);
        numberPickerMonth.setValue(viwMonth); // 月の初期値を設定

        NumberPicker numberPickerDay = view.findViewById(R.id.numberPickerDay);
        numberPickerDay.setMinValue(1);
        numberPickerDay.setMaxValue(getDaysInMonth(citrus.getCurYear(), citrus.getCurMonth())); // 日の初期値を設定
        numberPickerDay.setValue(viwDay); // 日の初期値を設定

        // 月が変更されたとき
        numberPickerMonth.setOnValueChangedListener((picker, oldVal, newVal) -> {
            int year = numberPickerYear.getValue();
            int daysInMonth = getDaysInMonth(year, newVal);
            numberPickerDay.setMaxValue(daysInMonth);
        });

        // 年が変更されたとき
        numberPickerYear.setOnValueChangedListener((picker, oldVal, newVal) -> {
            int month = numberPickerMonth.getValue();
            int daysInMonth = getDaysInMonth(newVal, month);
            numberPickerDay.setMaxValue(daysInMonth);
        });

        Spinner spinner = view.findViewById(R.id.select_todo_spinner);
        bookTitles = new ArrayList<>();
        bookTitles.add("本を選択");

        // Adapterの初期化を先に行う
        ArrayAdapter<String> adapter = new ArrayAdapter<>(requireContext(), androidx.appcompat.R.layout.support_simple_spinner_dropdown_item, bookTitles);
        adapter.setDropDownViewResource(androidx.appcompat.R.layout.support_simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);

        booksViewModel.getBookLiveData().observe(getViewLifecycleOwner(), new Observer<HashMap<Integer, Book>>() {
            @Override
            public void onChanged(HashMap<Integer, Book> integerBookHashMap) {
                if(integerBookHashMap != null){
                    for(int i : integerBookHashMap.keySet()){
                        bookTitles.add(integerBookHashMap.get(i).getTitle());
                        // 編集の場合、BookIdから対応するタイトルを探す
                        if (isEdit && integerBookHashMap.get(i).getTitle().equals(editBook.getTitle())){
                            selectBookNum = bookTitles.size() - 1; // 現在追加した位置を保持
                        }
                    }
                    // ArrayAdapterの更新を通知
                    adapter.notifyDataSetChanged();

                    // データがセットされた後にSpinnerに選択状態を設定
                    if (isEdit) {
                        spinner.setSelection(selectBookNum);
                    }
                } else {
                    bookTitles = new ArrayList<>();
                }
            }
        });

        booksViewModel.loadBooks(accountId, token);

        // 編集モードの場合、事前に本が選択されるようにSpinnerに設定
        if (isEdit) {
            spinner.setSelection(selectBookNum);
        }


        //キャンセルボタン処理
        Button cancelButton = view.findViewById(R.id.todo_cancel_button);
        cancelButton.setOnClickListener(v->{
            ((MainActivity)getActivity()).backFragment();
        });

        //削除ボタン処理
        Button deleteButton = view.findViewById(R.id.todo_delete_button);
        if (isEdit) {
            deleteButton.setVisibility(View.VISIBLE);  // 編集時ボタンを表示
        } else {
            deleteButton.setVisibility(View.INVISIBLE);  // 追加時ボタンを非表示
        }
        deleteButton.setOnClickListener(v->{
            todosViewModel.deleteTodo(accountId,editBook.getBookId(),editTodo.getYear(),
                    editTodo.getMonth(),editTodo.getDay(), editTodo.getTodoId(), token);
            ((MainActivity)getActivity()).backFragment();
        });

        //追加ボタン処理
        Button createButton = view.findViewById(R.id.todo_create_button);
        if (isEdit) {
            createButton.setText("完了"); //編集時
        } else {
            createButton.setText("追加"); //追加時
        }

        createButton.setOnClickListener(v->{
            int year = numberPickerYear.getValue(); // 設定年を取得
            int month = numberPickerMonth.getValue(); // 設定月を取得
            int day = numberPickerDay.getValue(); // 設定日を取得
            String title = titleField.getText().toString();
            Editable tmp = titleField.getText();
            if(tmp == null){
                Snackbar.make(view, "タイトルを入力してください", Snackbar.LENGTH_SHORT).show();
                return;
            }
            if(title == null || title.isEmpty()){
                Snackbar.make(view, "タイトルを入力してください", Snackbar.LENGTH_SHORT).show();
                return;
            }
            if(spinner.getSelectedItem().toString().equals("本を選択")){
                Snackbar.make(view, "本を選択してください", Snackbar.LENGTH_SHORT).show();
                return;
            }
            if(isEdit){
                //編集時
                //編集前のTodoは削除
                todosViewModel.deleteTodo(accountId,editBook.getBookId(),editTodo.getYear(),
                        editTodo.getMonth(),editTodo.getDay(), editTodo.getTodoId(), token);
                //編集後の年月日にTodoを追加
                todosViewModel.createTodo(accountId,spinner.getSelectedItemPosition(),year,month,day,title,token);

                ((MainActivity)getActivity()).backFragment();
            }else{
                //追加時
                todosViewModel.createTodo(accountId,spinner.getSelectedItemPosition(),year,month,day,title ,token);
                ((MainActivity)getActivity()).backFragment();
            }

        });
    }

    private int getDaysInMonth(int year, int month) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, month - 1); // Calendar.MONTHは0から始まるので-1する
        return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
    }

}