package com.example.leudaemialikeme.Fragment;

import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.example.leudaemialikeme.Activity.BaseActivity;
import com.example.leudaemialikeme.Activity.MainActivity;
import com.example.leudaemialikeme.Adapter.HistoryQuestionAdapter;
import com.example.leudaemialikeme.Model.Question;
import com.example.leudaemialikeme.R;
import com.example.leudaemialikeme.Utils.OkHttpUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * to handle interaction events.
 * Use the {@link QuestionHistoryFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class QuestionHistoryFragment extends Fragment {
    private static final String ARG_CATEGORY_TITLE = "category_title";
    private String collectCategoryTitle = "Default";
    private List<Question> questionAllList = new ArrayList<>();
    private SwipeRefreshLayout mSwipeRefreshLayout;
    private RecyclerView recyclerView;
    private boolean isPause = false;

    public QuestionHistoryFragment() {
        // Required empty public constructor
    }

    public static QuestionHistoryFragment newInstance(String collectCategoryTitle) {
        Bundle args = new Bundle();
        args.putString(ARG_CATEGORY_TITLE, collectCategoryTitle);
        QuestionHistoryFragment fragment = new QuestionHistoryFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        try {
            collectCategoryTitle = (String) getArguments().getString(ARG_CATEGORY_TITLE);
        }catch (java.lang.NullPointerException e)
        {
            System.out.println("TestFragment getArg error!");
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_question_history, container, false);
        recyclerView = (RecyclerView) view.findViewById(R.id.questionHistoryList);//获得视图
        LinearLayoutManager layoutManager;
        layoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(layoutManager);//建立线性布局
        final HistoryQuestionAdapter adapter = new HistoryQuestionAdapter(questionAllList, getContext());//创建适配器
        recyclerView.setItemAnimator(new DefaultItemAnimator());//设置动画效果
        recyclerView.setAdapter(adapter);
        mSwipeRefreshLayout = view.findViewById(R.id.refresh_layout);
//        mTextView = view.findViewById(R.id.tv_pull_down_refresh);
        getData();//获得数据
        handleDownPullUpdate();

        return view;
    }

    private void handleDownPullUpdate() {
        mSwipeRefreshLayout.setEnabled(true);
        mSwipeRefreshLayout.setColorSchemeResources(R.color.colorAccent,R.color.colorPrimary,R.color.light_grey);
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //不再显示提示正在刷新和刷新成功
//                mTextView.setText("正在刷新...");
                //被刷新时的操作
                //更新UI
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //更新成功后设置UI，停止更新
//                        mTextView.setText("刷新成功！！！");
                        mSwipeRefreshLayout.setRefreshing(false);
                    }
                },3000);
            }
        });
    }

    private void getData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    String url = MainActivity.SERVER_URL+"/my-servlet?action=historyQuestion&uid="+ BaseActivity.owner.getNetId()+"&type="+3;
                    Callback callback = new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            System.out.println("-----ERROR----");
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            String jsonStr = response.body().string();
                            Gson gson = new Gson();
                            Map<String, String> jsonMap= gson.fromJson(jsonStr,  new TypeToken<Map<String, String>>() {}.getType());
                            final String message=(String) jsonMap.get("message");
                            if (message.equals("success")) {
                                List<Question> questionList = gson.fromJson(jsonMap.get("questionList"), new TypeToken <List<Question>>(){}.getType());
                                questionAllList = questionList;
                                HistoryQuestionAdapter adapter = new HistoryQuestionAdapter(questionAllList, getContext());//创建适配器
                                recyclerView.setAdapter(adapter);
                            }
                        }
                    };
                    OkHttpUtil.asyGet(url,callback);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }
    @Override
    public void onPause() {
        super.onPause();
        isPause = true; //记录页面已经被暂停
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isPause){ //判断是否暂停
            isPause = false;
            getData();
            HistoryQuestionAdapter adapter = new HistoryQuestionAdapter(questionAllList, getContext());//创建适配器
            recyclerView.setAdapter(adapter);
        }

    }
}
