package com.example.cloudmusic.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

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

import com.example.cloudmusic.been.MineMusicListBeen;
import com.example.cloudmusic.R;
import com.example.cloudmusic.adapter.MusicAdapter;
import com.example.cloudmusic.utils.OkHttpUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

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

import okhttp3.Call;
import okhttp3.Response;


public class MusicFragment extends Fragment {


    private String id;
    private Handler mHandler;
    private View root;
    private List<MineMusicListBeen> list;

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

    @Override
    public void onStart() {
        super.onStart();
        initData();
        initUI();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        root = inflater.inflate(R.layout.fragment_music, container, false);
        SharedPreferences sp = getActivity().getPreferences(Context.MODE_PRIVATE);
        id = sp.getString("userId", "null");
        list = new ArrayList<>();
        return root;
    }

    @SuppressLint("HandlerLeak")
    private void initUI() {
        RecyclerView recycler = root.findViewById(R.id.music_recycler);
        MusicAdapter adapter = new MusicAdapter(list, root.getContext());
        LinearLayoutManager manager = new LinearLayoutManager(root.getContext());
        recycler.setAdapter(adapter);
        recycler.setLayoutManager(manager);

        mHandler = new Handler() {
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case 1:
                        list.clear();
                        list.addAll((Collection<? extends MineMusicListBeen>) msg.obj);
                        adapter.notifyDataSetChanged();
                        break;
                }
            }
        };
    }

    private void initData() {
        OkHttpUtil util = new OkHttpUtil();
        System.out.println(id);
        util.sendGetRequest("http://192.168.86.158:3000/user/playlist?uid=" + id, new OkHttpUtil.OkhttpInterface() {
            @Override
            public void success(Call call, Response response) {
                try {
                    String string = response.body().string();
                    JSONObject object = new JSONObject(string);
                    JSONArray result = object.optJSONArray("playlist");
                    List<MineMusicListBeen> list = new ArrayList<>();
                    for (int i = 0; i < result.length(); i++) {
                        MineMusicListBeen been = new MineMusicListBeen();
                        JSONObject json = (JSONObject) result.get(i);
                        String name = json.optString("name");
                        String songNumber = json.optString("trackCount");
                        String coverImgUrl = json.optString("coverImgUrl");
                        String songListId = json.optString("id");
                        JSONObject creator = json.optJSONObject("creator");
                        String author = creator.optString("nickname");
                        String authorId = creator.optString("userId");
                        been.setAuthor(author);
                        been.setAuthorId(authorId);
                        been.setName(name);
                        been.setCount(songNumber);
                        been.setCoverImgUrl(coverImgUrl);
                        been.setListId(songListId);
                        list.add(been);
                    }

                    Message msg = new Message();
                    msg.what = 1;
                    msg.obj = list;
                    mHandler.sendMessage(msg);
                } catch (IOException | JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void failure(Call call, IOException e) {

            }
        });
    }
}