package com.example.cloudmusic.activity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
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.GecAdapter;
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.Collection;
import java.util.List;
import java.util.StringJoiner;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Response;

public class PlayerActivity extends AppCompatActivity {

    private String id = "2158973221";
    private TextView song;
    private TextView author;
    private TextView title;
    private TextView vipText;
    private TextView maxTime;
    private ImageView img;
    private Handler mHandler;
    private List<String> list;
    private RecyclerView recycler;
    private GecAdapter adapter;
    private String listName;

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

        initUI();

        initData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        getIntent().removeExtra("id");
        getIntent().removeExtra("songListName");
    }

    @SuppressLint({"SetTextI18n", "HandlerLeak"})
    private void initUI() {
        if (getIntent().getExtras() != null) {
            String data = getIntent().getExtras().getString("id");
            if (data != null) {
                id = getIntent().getExtras().getString("id");
                listName = getIntent().getExtras().getString("songListName");
                initSong();
            } else {
                System.out.println("数据为空");
            }
        } else {
            System.out.println("没得");
        }

        //listName = intent.getExtras().getString("songListName");
        //id = intent.getExtras().getString("id");
        song = findViewById(R.id.player_songName);
        author = findViewById(R.id.player_authorName);
        img = findViewById(R.id.player_img);
        title = findViewById(R.id.player_title);
        vipText = findViewById(R.id.player_vip);
        maxTime = findViewById(R.id.player_song_maxTime);
        list = new ArrayList<>();

        findViewById(R.id.player_back).setOnClickListener(v -> finish());


        LinearLayout page1 = findViewById(R.id.player_page);
        TextView back = findViewById(R.id.gec_back);
        LinearLayout page2 = findViewById(R.id.player_page2);
        page1.setOnClickListener(v -> {
            page1.setVisibility(View.GONE);
            page2.setVisibility(View.VISIBLE);
        });
        back.setOnClickListener(v -> {
            page2.setVisibility(View.GONE);
            page1.setVisibility(View.VISIBLE);
        });

        mHandler = new Handler() {
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case 1:
                        list.addAll((Collection<? extends String>) msg.obj);
                        adapter.notifyDataSetChanged();
                        break;
                    case 2:
                        ListBeen.Song song2 = (ListBeen.Song) msg.obj;
                        String imgPath = song2.getSongImg();
                        String songLength = song2.getDt();
                        boolean vip = song2.isVip();
                        String songName = song2.getSongName();
                        String authorName = song2.getAuthorName();
                        int time = (int) TimeUnit.MILLISECONDS.toSeconds(Integer.parseInt(songLength));
                        maxTime.setText("0" + time / 60 + ":" + time % 60);
                        song.setText(songName);
                        author.setText(authorName + " >");
                        title.setText(listName);
                        if (vip) {
                            vipText.setVisibility(View.VISIBLE);
                        }
                        Glide.with(PlayerActivity.this)
                                .load(imgPath)
                                .placeholder(R.drawable.text)
                                .into(img);
                }
            }
        };

        recycler = findViewById(R.id.player_recycler);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        adapter = new GecAdapter(list, this);
        recycler.setLayoutManager(manager);
        recycler.setAdapter(adapter);
    }

    private void initData() {
        OkHttpUtil util = OkHttpUtil.getInstance();
        util.sendGetRequest("http://192.168.86.158:3000/lyric?id=" + id, new OkHttpUtil.OkhttpInterface() {
            @Override
            public void success(Call call, Response response) {
                try {
                    String body = response.body().string();
                    JSONObject object = new JSONObject(body);
                    JSONObject json = object.optJSONObject("lrc");
                    String content = json.optString("lyric");
                    String[] split = content.split("\\n");
                    List<String> list = new ArrayList<>();
                    for (String s : split) {
                        int start = s.indexOf("[");
                        int end = s.indexOf("]");
                        String substring = s.substring(start, end + 1);
                        s = s.replace(substring, "");
                        list.add(s);
                    }
                    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) {

            }
        });
    }
    private void initSong() {
        OkHttpUtil util = OkHttpUtil.getInstance();
        util.sendGetRequest("http://192.168.86.158:3000/song/detail?ids=" + id, new OkHttpUtil.OkhttpInterface() {
            @Override
            public void success(Call call, Response response) {
                try {
                    String body = response.body().string();
                    JSONObject j = new JSONObject(body);
                    JSONArray arr = j.optJSONArray("songs");
                    JSONObject json = (JSONObject) arr.get(0);
                    String singName = json.optString("name");
                    JSONArray arr2 = json.getJSONArray("ar");
                    StringJoiner authorName = null;
                    for (int i = 0; i < arr2.length(); i++) {
                        JSONObject json1 = (JSONObject) arr2.get(i);
                        String name = json1.optString("name");
                        authorName = new StringJoiner("/");
                        authorName.add(name);
                    }
                    JSONObject json2 = json.optJSONObject("al");
                    String imgURL = json2.optString("picUrl");
                    String fee = json.optString("fee");
                    String id = json.optString("id");
                    String dt = json.optString("dt");
                    ListBeen.Song song = new ListBeen.Song();
                    if (!fee.equals("0")) {
                        song.setVip(true);
                    }
                    song.setId(id);
                    song.setSongName(singName);
                    song.setAuthorName(String.valueOf(authorName));
                    song.setDt(dt);
                    song.setSongImg(imgURL);
                    Message msg = new Message();
                    msg.what = 2;
                    msg.obj = song;
                    mHandler.sendMessage(msg);
                } catch (IOException | JSONException e) {
                    e.printStackTrace();
                }
            }

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

            }
        });
    }
}