package com.example.cloudmusic.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

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

import com.bumptech.glide.Glide;
import com.example.cloudmusic.R;
import com.example.cloudmusic.adapter.SongAdapter;
import com.example.cloudmusic.adapter.StartDecoration;
import com.example.cloudmusic.been.ListBeen;
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.List;

import okhttp3.Call;
import okhttp3.Response;

public class SongListActivity extends AppCompatActivity {

    private String id;
    private ListBeen been;
    private Handler mHandler;
    private TextView title;
    private TextView title1;
    private TextView jieS;
    private TextView fenX;
    private TextView pinL;
    private TextView shouC;
    private TextView songNumber;
    private ImageView back;
    private RecyclerView recycler;
    private  List<ListBeen.Song> songs;
    private String name = "";
    private ScrollView scroll;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_song_list);
        initUI();
    }

    @SuppressLint("HandlerLeak")
    private void initUI() {
        Intent intent = getIntent();
        id = intent.getExtras().getString("id");
        name = intent.getExtras().getString("name");
        Button shit = findViewById(R.id.list_item_back);
        title1 = findViewById(R.id.list_item_title);
        jieS = findViewById(R.id.list_item_jieshao);
        fenX = findViewById(R.id.list_item_fenx);
        pinL = findViewById(R.id.list_item_pinl);
        shouC = findViewById(R.id.list_item_shouc);
        songNumber = findViewById(R.id.list_item_song_number);
        back = findViewById(R.id.list_item_back2);
        recycler = findViewById(R.id.song_recycler);
        scroll = findViewById(R.id.scroll);

       // initListener();

        shit.setOnClickListener(view -> {
            finish();
        });
        startData();
        songs = new ArrayList<>();
        LinearLayoutManager manager = new LinearLayoutManager(SongListActivity.this);
        SongAdapter adapter = new SongAdapter(songs,SongListActivity.this);
        recycler.setAdapter(adapter);
        recycler.setLayoutManager(manager);
        recycler.setNestedScrollingEnabled(false);
        recycler.addItemDecoration(new StartDecoration(this));
       // recycler.setHasFixedSize(true);

        mHandler = new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                switch (msg.what){
                    case 1:
                        been = (ListBeen) msg.obj;
                        if (been.getName().length()>8){
                        title1.setText(been.getName().substring(0,8));
                        }else{
                            title1.setText(been.getName().substring(0,been.getName().length()));
                        }
                        jieS.setText(been.getDescription());
                        fenX.setText(been.getShareCount());
                        pinL.setText(been.getCommentCount());
                        shouC.setText(been.getSubscribedCount());
                        songNumber.setText("( "+been.getTrackCount()+" )");
                        Glide.with(SongListActivity.this)
                                .load(been.getImgURL())
                                .placeholder(R.drawable.cloudmusic_gray)
                                .into(back);
                    case 2:
                      //  songs.addAll((Collection<? extends ListBeen.Song>) msg.obj);
                        been.setSongList(songs);
                        System.out.println(been.getSongList().size());
                        adapter.notifyDataSetChanged();
                }
            }
        };

       // FrameLayout fragment = findViewById(R.id.abc_h);
       // LinearLayout layout = findViewById(R.id.add_c);
       // FrameLayout frameLayout = new FrameLayout(this);
       // frameLayout.addView(layout);
       // frameLayout.addView(fragment);

       // setContentView(frameLayout);
    }

    @SuppressLint("ClickableViewAccessibility")
    private void initListener() {
        //recycler.setOnTouchListener((view, motionEvent) -> true);
        scroll.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (motionEvent.getAction() == MotionEvent.ACTION_MOVE) {
                    // 取消RecyclerView的滚动事件
                    recycler.dispatchTouchEvent(MotionEvent.obtain(motionEvent.getDownTime(), motionEvent.getEventTime(), MotionEvent.ACTION_CANCEL, motionEvent.getX(), motionEvent.getY(), motionEvent.getMetaState()));
                }
                return false;
            }
        });
    }

    private void startData() {
        OkHttpUtil okHttpUtil = new OkHttpUtil();
        okHttpUtil.sendGetRequest("http://192.168.86.158:3000/playlist/detail?id="+id, new OkHttpUtil.OkhttpInterface() {
            @Override
            public void success(Call call, Response response) {
                try {
                    String body = response.body().string();
                    JSONObject j = new JSONObject(body);
                    JSONObject result = j.optJSONObject("playlist");
                    String id = result.optString("id");
                    String name = result.optString("name");
                    String imgURL = result.optString("coverImgUrl");
                    String description = result.optString("description");
                    String trackCount = result.optString("trackCount");
                    String subscribedCount = result.optString("subscribedCount");
                    String shareCount = result.optString("shareCount");
                    String commentCount = result.optString("commentCount");
                    ListBeen been = new ListBeen();
                    been.setDescription(description);
                    been.setCommentCount(commentCount);
                    been.setImgURL(imgURL);
                    been.setName(name);
                    been.setTrackCount(trackCount);
                    been.setSubscribedCount(subscribedCount);
                    been.setShareCount(shareCount);
                    Message msg = new Message();
                    msg.what = 1;
                    msg.obj = been;
                    mHandler.sendMessage(msg);

                } catch (JSONException | IOException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void failure(Call call, IOException e) {

            }
        });

        okHttpUtil.sendGetRequest("http://192.168.86.158:3000/playlist/track/all?id="+id, new OkHttpUtil.OkhttpInterface() {
            @Override
            public void success(Call call, Response response) {
                String body;
                List<ListBeen.Song> list = new ArrayList<>();
                try {
                    body = response.body().string();
                    JSONObject j = new JSONObject(body);
                    JSONArray result = j.optJSONArray("songs");
                    for (int i = 0; i < result.length(); i++) {
                        JSONObject json = (JSONObject) result.get(i);
                        String singName = json.optString("name");
                        JSONObject json1 = (JSONObject) json.getJSONArray("ar").get(0);
                        String authorName = json1.optString("name");
                        JSONObject json2 = json.optJSONObject("al");
                        String ListName = json2.optString("name");
                        String imgURL = json2.optString("picUrl");
                        String fee = json.optString("fee");
                        String mv = json.optString("mv");
                        String id = json.optString("id");
                        String dt = json.optString("dt");
                        ListBeen.Song song = new ListBeen.Song();
                        if (!fee.equals("0")){
                            song.setVip(true);
                        }
                        if (!mv.equals("0")){
                            song.setMv(true);
                        }
                        song.setId(id);
                        song.setSongName(singName);
                        song.setAuthorName(authorName);
                        song.setListName(ListName);
                        song.setSongNumber(String.valueOf(i+1));
                        song.setSongListName(name);
                        song.setDt(dt);
                        song.setSongImg(imgURL);
                        list.add(song);
                    }
                    Message msg = new Message();
                    msg.what = 2;
                    msg.obj = list;
                    songs.addAll(list);
                    mHandler.sendMessage(msg);
                } catch (IOException | JSONException e) {
                    e.printStackTrace();
                }
            }

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

            }
        });
    }
}