package com.example.leudaemialikeme.Fragment;

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

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 android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.leudaemialikeme.Activity.BaseActivity;
import com.example.leudaemialikeme.Activity.MainActivity;
import com.example.leudaemialikeme.Adapter.HistoryNewsAdapter;
import com.example.leudaemialikeme.Model.News;
import com.example.leudaemialikeme.R;
import com.example.leudaemialikeme.Utils.OkHttpUtil;
import com.example.leudaemialikeme.Utils.TimeUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.sql.Timestamp;
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 NewsHistoryFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class NewsHistoryFragment extends Fragment {
    private static final String ARG_CATEGORY_TITLE = "category_title";
    private String collectCategoryTitle = "Default";
    private List<News> collectList = new ArrayList<>();
    private SwipeRefreshLayout mSwipeRefreshLayout;

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

    public static NewsHistoryFragment newInstance(String collectCategoryTitle) {
        Bundle args = new Bundle();
        args.putString(ARG_CATEGORY_TITLE, collectCategoryTitle);
        NewsHistoryFragment fragment = new NewsHistoryFragment();
        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_news_history, container, false);
        getData();//获得数据
        RecyclerView recycleView = (RecyclerView) view.findViewById(R.id.newsHistoryList);//获得视图
        LinearLayoutManager layoutManager;
        layoutManager = new LinearLayoutManager(getActivity());
        recycleView.setLayoutManager(layoutManager);//建立线性布局
        final HistoryNewsAdapter adapter = new HistoryNewsAdapter(collectList);//创建适配器
        recycleView.setItemAnimator(new DefaultItemAnimator());//设置动画效果
        recycleView.setAdapter(adapter);
        mSwipeRefreshLayout = view.findViewById(R.id.refresh_layout);
//        mTextView = view.findViewById(R.id.tv_pull_down_refresh);
        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(){
//        News collect1 = new News(1,1,"1","临时测试浏览记录版","能解决的！", TimeUtil.stringToTime("2022-01-07 12:12:12"),3);
//        collectList.add(collect1);
//        News collect2 = new News(1,1,"1","临时测试2浏览记录版","能解决的！",TimeUtil.stringToTime("2022-01-07 12:12:12"),5);
//        collectList.add(collect2);

        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    String url = MainActivity.SERVER_URL+"/my-servlet?action=historyNews&uid="+ BaseActivity.owner.getNetId()+"&type="+1;
                    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<News> newsList = gson.fromJson(jsonMap.get("newsList"), new TypeToken <List<News>>(){}.getType());
                                for(int i=0;i<newsList.size();i++){
                                    News startNews = newsList.get(i);
                                    int nid = startNews.getNid();
                                    int sid = startNews.getSid();
                                    String stype = startNews.getStype();
                                    String stittle = startNews.getStittle();
                                    String scontent = startNews.getScontent();
                                    Timestamp stime = startNews.getStime();
                                    int sbrowseNum = startNews.getSbrowseNum();
                                    News endNews = new News(nid,sid,stype,stittle,scontent,stime,sbrowseNum);
                                    collectList.add(endNews);
                                }
                            }
                        }
                    };
                    OkHttpUtil.asyGet(url,callback);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }
}