package com.example.tampopo_client.views;

import android.content.Context;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.tampopo_client.R;
import com.example.tampopo_client.Tampopo;
import com.example.tampopo_client.viewmodels.FriendViewModel;
import com.example.tampopo_client.views.placeholder.FriendContent;

import java.util.List;
import androidx.lifecycle.Observer;

/**
 * フレンド一覧を表示するフラグメント
 */
public class FriendListFragment extends Fragment {

    // TODO: Customize parameter argument names
    private static final String ARG_COLUMN_COUNT = "column-count";
    // TODO: Customize parameters
    private int mColumnCount = 1;

    private MyFriendRecyclerViewAdapter adapter;

    /**
     * Mandatory empty constructor for the fragment manager to instantiate the
     * fragment (e.g. upon screen orientation changes).
     */
    public FriendListFragment() {
    }

    // TODO: Customize parameter initialization
//    @SuppressWarnings("unused")
//    public static FriendListFragment newInstance(int columnCount) {
//        FriendListFragment fragment = new FriendListFragment();
//        Bundle args = new Bundle();
//        args.putInt(ARG_COLUMN_COUNT, columnCount);
//        fragment.setArguments(args);
//        return fragment;
//    }

    public static FriendListFragment newInstance(int columnCount) {
        FriendListFragment fragment = new FriendListFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_COLUMN_COUNT, columnCount);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getArguments() != null) {
            mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT);
        }
    }

//    @Override
//    public View onCreateView(LayoutInflater inflater, ViewGroup container,
//                             Bundle savedInstanceState) {
//        View view = inflater.inflate(R.layout.fragment_friend_list_list, container, false);
//
//        RecyclerView recyclerView = view.findViewById(R.id.list);
//        Context context = view.getContext();
//
//        // Add some sample items.
//        //for (int i = 1; i <= 30; i++) {
//        //    FriendContent.addItem(new FriendContent.FriendItem(Integer.toString(i), "ユーザ" + i));
//        //}
//
//        // Set the adapter
//        if (view instanceof RecyclerView) {
//            Context context = view.getContext();
//            RecyclerView recyclerView = (RecyclerView) view;
//            if (mColumnCount <= 1) {
//                recyclerView.setLayoutManager(new LinearLayoutManager(context));
//            } else {
//                recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
//            }
//            recyclerView.setAdapter(new MyFriendRecyclerViewAdapter(FriendContent.ITEMS));
//        }
//        adapter = new MyFriendRecyclerViewAdapter(FriendContent.ITEMS);
//        recyclerView.setAdapter(adapter);
//        return view;
//    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_friend_list_list, container, false);

        RecyclerView recyclerView = view.findViewById(R.id.list);
        Context context = view.getContext();

        if (mColumnCount <= 1) {
            recyclerView.setLayoutManager(new LinearLayoutManager(context));
        } else {
            recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
        }

        // adapterをここで初期化
        adapter = new MyFriendRecyclerViewAdapter(FriendContent.ITEMS);
        recyclerView.setAdapter(adapter);

        return view;
    }



//    @Override
//    public void onViewCreated(View view, Bundle savedInstanceState) {
//        super.onViewCreated(view, savedInstanceState);
//        FriendViewModel friendViewModel = new ViewModelProvider(this).get(FriendViewModel.class);
//
//        String userId = ((Tampopo) ((FriendActivity) view.getContext()).getApplication()).getUserId;
//        String token = ((Tampopo) ((FriendActivity) view.getContext()).getApplication()).getToken;
//        friendViewModel.loadFriends(userId, token);
//
//        friendViewModel.getFriendIdsLiveData().observe(getViewLifecycleOwner(), new Observer<List<String>>() {
//
//            @Override
//            public void onChanged(List<String> friendIds) {
//                for (String i : friendIds) {
//                    FriendContent.addItem(new FriendContent.FriendItem(i, ""));
//                }
//                adapter.notifyDataSetChanged();
//            }
//        });
//    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        FriendViewModel friendViewModel = new ViewModelProvider(this).get(FriendViewModel.class);

//自分の情報を取得する
        Tampopo app = (Tampopo) requireActivity().getApplication();
        String userId = app.getUserId();
        String token  = app.getToken();

//サーバーからフレンド一覧を取得する
        friendViewModel.loadFriends(userId, token);

//一旦旧コードをコメントアウトしました。
//        friendViewModel.getFriendIdsLiveData().observe(getViewLifecycleOwner(), new Observer<List<String>>() {
//            @Override
//            public void onChanged(List<String> friendIds) {
//                // 一度リセットして新しいリストを追加
//                FriendContent.clear();
//                for (String id : friendIds) {
//                    FriendContent.addItem(new FriendContent.FriendItem(id, ""));
//                }
//                // adapterがクラス変数なのでここで使える
//                adapter.notifyDataSetChanged();
//            }
//        });
        friendViewModel.getFriendIdsLiveData().observe(getViewLifecycleOwner(), friendIds -> {
            FriendContent.clear();
            if (friendIds != null) {
                for (String id : friendIds) {
                    FriendContent.addItem(new FriendContent.FriendItem(id, ""));
                }
            }
            adapter.notifyDataSetChanged();
        });
    }
}