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

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.text.Editable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TimePicker;

import com.example.citrusclient.Citrus;
import com.example.citrusclient.R;
import com.example.citrusclient.models.Book;
import com.example.citrusclient.models.Schedule;
import com.example.citrusclient.viewmodels.BooksViewModel;
import com.example.citrusclient.viewmodels.ScheduleViewModel;
import com.google.android.material.snackbar.Snackbar;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link CreateScheduleFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class CreateScheduleFragment 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;

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

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


    BooksViewModel booksViewModel;
    ScheduleViewModel scheduleViewModel;


    List<String> bookTitles;


    String accountId;
    String token;

    private int selectBookNum;
    //編集用変数
    private boolean isEdit;
    private Schedule editSchedule;
    private Book editBook;
    private String viwTitle;
    private int viwStartYear;
    private int viwStartMonth;
    private int viwStartDay;
    private int viwStartHour;
    private int viwStartMin;
    private int viwEndYear;
    private int viwEndMonth;
    private int viwEndDay;
    private int viwEndHour;
    private int viwEndMin;


    //追加用コンストラクタ
    public CreateScheduleFragment(int viwYear, int viwMonth, int viwDay) {
        this.isEdit = false;
        this.viwStartYear = viwYear;
        this.viwStartMonth = viwMonth;
        this.viwStartDay = viwDay;//Homeからは表示している日付、calendarからは今日の日付
        viwStartHour = 0;
        viwStartMin = 0;
        viwEndYear = viwYear;
        viwEndMonth = viwMonth;
        viwEndDay =  viwDay;
        viwEndHour = 23;
        viwEndMin = 59;
        viwTitle = "";
    }

    //編集用コンストラクタ
    public CreateScheduleFragment(Schedule editSchedule, Book editBook){
        this.isEdit = true;
        this.editSchedule = editSchedule;
        this.editBook = editBook;
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm");
        LocalDateTime startTime = LocalDateTime.parse(this.editSchedule.getStartTime(), formatter);
        viwStartYear = startTime.getYear();
        viwStartMonth = startTime.getMonthValue();
        viwStartDay = startTime.getDayOfMonth();
        viwStartHour = startTime.getHour();
        viwStartMin = startTime.getMinute();
        LocalDateTime endTime = LocalDateTime.parse(this.editSchedule.getEndTime(), formatter);
        viwEndYear = endTime.getYear();
        viwEndMonth = endTime.getMonthValue();
        viwEndDay = endTime.getDayOfMonth();
        viwEndHour = endTime.getHour();
        viwEndMin = endTime.getMinute();
        viwTitle = editSchedule.getTitle();

    }

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

        booksViewModel = new ViewModelProvider(this).get(BooksViewModel.class);
        scheduleViewModel = new ViewModelProvider(this).get(ScheduleViewModel.class);

        Citrus citrus = (Citrus)(getActivity().getApplication());
        accountId = citrus.getAccountId();
        token = citrus.getToken();

    }


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

        Button startDateButton = view.findViewById(R.id.start_date_button);
        Button startTimeButton = view.findViewById(R.id.start_time_button);
        Button endDateButton = view.findViewById(R.id.end_date_button);
        Button endTimeButton = view.findViewById(R.id.end_time_button);

        startDateButton.setText(viwStartYear + "/" + String.format("%02d", (viwStartMonth)) + "/" + String.format("%02d", viwStartDay));
        if(!isEdit) {
            startTimeButton.setText("00:00");
        }else{
            startTimeButton.setText(String.format("%02d", viwStartHour) + ":" + String.format("%02d", viwStartMin));
        }
        endDateButton.setText(viwEndYear + "/" + String.format("%02d", (viwEndMonth)) + "/" + String.format("%02d", viwEndDay));
        if(!isEdit) {
            endTimeButton.setText("23:59");
        }else{
            endTimeButton.setText(String.format("%02d", viwEndHour) + ":" + String.format("%02d", viwEndMin));
        }

        startDateButton.setOnClickListener(v->{
            DatePickerDialog datePickerDialog = new DatePickerDialog(requireContext(), new DatePickerDialog.OnDateSetListener() {
                @Override
                public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                    String date = year + "/" + String.format("%02d", (month+1)) + "/" + String.format("%02d", dayOfMonth);
                    startDateButton.setText(date);
                }
            }, viwStartYear, viwStartMonth-1, viwStartDay);
            datePickerDialog.show();
        });
        startTimeButton.setOnClickListener(v -> {
            TimePickerDialog timePickerDialog = new TimePickerDialog(requireContext(), new TimePickerDialog.OnTimeSetListener() {
                @Override
                public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                    String time = String.format("%02d", (hourOfDay)) + ":" + String.format("%02d", (minute));
                    startTimeButton.setText(time);
                }
            }, viwStartHour, viwStartMin, true);
            timePickerDialog.show();
        });
        endDateButton.setOnClickListener(v->{
            DatePickerDialog datePickerDialog = new DatePickerDialog(requireContext(), new DatePickerDialog.OnDateSetListener() {
                @Override
                public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                    String date = year + "/" + String.format("%02d", (month+1)) + "/" + String.format("%02d", dayOfMonth);
                    endDateButton.setText(date);
                }
            }, viwEndYear, viwEndMonth-1, viwEndDay);
            datePickerDialog.show();
        });
        endTimeButton.setOnClickListener(v -> {
            TimePickerDialog timePickerDialog = new TimePickerDialog(requireContext(), new TimePickerDialog.OnTimeSetListener() {
                @Override
                public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                    String time = String.format("%02d", (hourOfDay)) + ":" + String.format("%02d", (minute));
                    endTimeButton.setText(time);
                }
            }, viwEndHour, viwEndMin, true);
            timePickerDialog.show();
        });

        Switch allDaySwitch = view.findViewById(R.id.all_day_switch);
        allDaySwitch.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if(isChecked){
                startTimeButton.setTextColor(Color.GRAY);
                startTimeButton.setText("00:00");
                endDateButton.setTextColor(Color.GRAY);
                endDateButton.setText(startDateButton.getText());
                endTimeButton.setTextColor(Color.GRAY);
                endTimeButton.setText("23:59");
            }else{
                startTimeButton.setTextColor(Color.BLACK);
                endDateButton.setTextColor(Color.BLACK);
                endTimeButton.setTextColor(Color.BLACK);
            }
            startTimeButton.setEnabled(!isChecked);
            endDateButton.setEnabled(!isChecked);
            endTimeButton.setEnabled(!isChecked);
        });

        Spinner spinner = view.findViewById(R.id.select_schedule_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(editBook == null) break; //本に所属していない場合はばいばい
                        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.schedule_cancel_button);
        cancelButton.setOnClickListener(v->{
            ((MainActivity)getActivity()).backFragment();
        });

        //削除ボタン処理
        Button deleteButton = view.findViewById(R.id.schedule_delete_button);
        if (isEdit) {
            deleteButton.setVisibility(View.VISIBLE);  // 編集時ボタンを表示
        } else {
            deleteButton.setVisibility(View.INVISIBLE);  // 追加時ボタンを非表示
        }
        deleteButton.setOnClickListener(v->{
            scheduleViewModel.deleteScheduleById(accountId,viwStartYear,viwStartMonth,viwStartDay,
                    editSchedule.getScheduleId(), token);
            ((MainActivity)getActivity()).backFragment();
        });

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

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

        confirmButton.setOnClickListener(v -> {
            String[] dates = ((String)startDateButton.getText()).split("/");
            int year = Integer.parseInt(dates[0]);
            int month = Integer.parseInt(dates[1]);
            int day = Integer.parseInt(dates[2]);
            Editable tmp = scheduleTitle.getText();
            if(tmp == null){
                Snackbar.make(view, "タイトルを入力してください", Snackbar.LENGTH_SHORT).show();
                return;
            }
            String title = scheduleTitle.getText().toString();
            if(title == null || title.isEmpty()){
                Snackbar.make(view, "タイトルを入力してください", Snackbar.LENGTH_SHORT).show();
                return;
            }
            //
            String startDateTime = startDateButton.getText() + " " + startTimeButton.getText();
            String endDateTime = endDateButton.getText() + " " + endTimeButton.getText();
            Log.i("lkjfda", startDateTime + ":" + endDateTime);
            Log.i("lkjsa", "" + spinner.getSelectedItemPosition());

            if(isEdit){
                //編集時
                scheduleViewModel.deleteScheduleById(accountId,viwStartYear,viwStartMonth,viwStartDay,
                        editSchedule.getScheduleId(), token);
                scheduleViewModel.createSchedule(accountId, year, month, day, token, title, startDateTime, endDateTime,
                        spinner.getSelectedItemPosition());
                ((MainActivity)getActivity()).backFragment();
            }else{
                //追加時
                scheduleViewModel.createSchedule(accountId, year, month, day, token, title, startDateTime, endDateTime,
                        spinner.getSelectedItemPosition());
                ((MainActivity)getActivity()).backFragment();
            }
        });


    }

}