package com.hi.music.player.adapter;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.OptIn;
import androidx.lifecycle.Observer;
import androidx.media3.common.util.UnstableApi;
import androidx.media3.exoplayer.offline.Download;
import androidx.media3.exoplayer.offline.DownloadRequest;
import androidx.media3.exoplayer.offline.DownloadService;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.google.gson.Gson;
import com.hi.music.player.MusicApplication;
import com.hi.music.player.R;
import com.hi.music.player.api.onCheckDownload;
import com.hi.music.player.databinding.ItemLikeSongBinding;
import com.hi.music.player.databinding.ItemSingerBinding;
import com.hi.music.player.helper.CommonUtils;
import com.hi.music.player.javabean.BoxDownloadSong;
import com.hi.music.player.javabean.BoxLikeSong;
import com.hi.music.player.javabean.CustomerDownload;
import com.hi.music.player.javabean.response.ResponsePlayUrl;
import com.hi.music.player.javabean.response.child.ResponseSingle;
import com.hi.music.player.media3.MyDownloadService;
import com.hi.music.player.media3.MyMediaControllerManager;
import com.hi.music.player.network.JsonHelper;
import com.hi.music.player.network.RetrofitManager;
import com.hi.music.player.ui.activity.viewmodel.VMApplication;

import org.json.JSONObject;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

import okhttp3.ResponseBody;

public class AdapterLikeSong extends BaseAdapter<BoxLikeSong, ItemLikeSongBinding> {

    private VMApplication vmApplication;

    private List<Pair<Boolean, String>> status = new ArrayList<>();

    @Override
    protected ItemLikeSongBinding getViewBinding(ViewGroup parent) {
        return ItemLikeSongBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false);
    }


    public AdapterLikeSong(Context mContext, VMApplication vm) {
        super(mContext);
        vmApplication = vm;


    }

    public void updateDownloadStatus(boolean isSuccess, int position, String videoId) {
        status.add(new Pair<>(isSuccess, videoId));
        notifyItemChanged(position);
    }

    @OptIn(markerClass = UnstableApi.class)
    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        VHolder<ItemLikeSongBinding> itemHolder = (VHolder<ItemLikeSongBinding>) holder;
        ItemLikeSongBinding vb = itemHolder.getVb();
        BoxLikeSong boxLikeSong = data.get(position);
        String videoId = boxLikeSong.getVideoId();

        if (position == data.size()-1){
            vb.place.setVisibility(View.VISIBLE);
        }else {
            vb.place.setVisibility(View.GONE);
        }


        for(Pair<Boolean,String> pair:status){
            if(pair.second.equals(videoId)){
                vb.imDownload.setSelected(pair.first);
                vb.imDownload.setVisibility(View.VISIBLE);
                vb.downloadPb.setVisibility(View.GONE);
                CommonUtils.LogMsg("--------------------状态更新");
            }
        }

        MyDownloadService.queryIsDownload(videoId, new onCheckDownload() {
            @Override
            public void onHasDownload(CustomerDownload customerDownload) {
                boolean download = customerDownload.isDownload();
                if (download) {
                    vb.imDownload.setSelected(true);
                } else {
                    vb.imDownload.setSelected(false);
                }
            }
        });
        vb.layoutDownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (vb.imDownload.isSelected()) {
                    //已经下载
                    Toast.makeText(mContext,mContext.getText(R.string.text_has_downloaded),Toast.LENGTH_SHORT).show();
                    return;
                }

                vb.imDownload.setVisibility(View.GONE);
                vb.downloadPb.setVisibility(View.VISIBLE);
                RetrofitManager.getInstance().getPlayUrl(videoId, new com.hi.music.player.api.RequestListener<ResponseBody>() {

                    @Override
                    public void onFail(String errorMsg) {
                        CommonUtils.LogMsg("-------------onFail");

                    }

                    @Override
                    public void onSuccess(JSONObject data) {
//                JSONObject jsonObject = CommonUtils.toJsonObject(data);
                        if (data != null) {
                            ResponsePlayUrl responsePlayUrl = JsonHelper.ResolvePlayUrlJson(data);
                            if (responsePlayUrl == null) {
                                // TODO: 2024/9/27
                                return;
                            }
                            String videoUrlMedium = responsePlayUrl.getVideoUrlMedium();

                            BoxDownloadSong downloadSong = new BoxDownloadSong();
                            downloadSong.setVideoId(videoId);
                            downloadSong.setCovert(String.valueOf(boxLikeSong.getCovert()));
                            downloadSong.setSongName((String) boxLikeSong.getSongName());
                            downloadSong.setSingerName((String) boxLikeSong.getSingerName());
                            downloadSong.setDuration((String) boxLikeSong.getDuration());
                            downloadSong.setDurationMs(boxLikeSong.getDurationMs());
                            downloadSong.setVideoUrl(videoUrlMedium);
                            Gson gson = new Gson();
                            String info = gson.toJson(downloadSong);
                            byte[] bytes = info.getBytes(StandardCharsets.UTF_8);

                            DownloadRequest downloadRequest = new DownloadRequest.Builder(videoId, Uri.parse(videoUrlMedium))
                                    .setMimeType("video/mp4")
                                    .setData(bytes)
                                    .build();


                            DownloadService.sendAddDownload(
                                    mContext,
                                    MyDownloadService.class, // 上面定义的下载服务类
                                    downloadRequest,
                                    true // 是否在前台运行
                            );
                            if (homeItemClickListener != null) {
                                homeItemClickListener.onDownloadSong(videoId, itemHolder.getAbsoluteAdapterPosition());
                            }

                        }


                    }
                });


            }
        });
        Glide.with(MusicApplication.myApplication)
                .asDrawable()
                .load(boxLikeSong.getCovert())
                .apply(RequestOptions.bitmapTransform(new RoundedCorners(CommonUtils.dpToPx(4))))
                .placeholder(R.mipmap.im_placeholder)
                .listener(new RequestListener<Drawable>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, @Nullable Object model, @NonNull Target<Drawable> target, boolean isFirstResource) {
                        CommonUtils.LogMsg(e.getMessage());
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(@NonNull Drawable resource, @NonNull Object model, Target<Drawable> target, @NonNull DataSource dataSource, boolean isFirstResource) {
                        return false;
                    }
                })
                .into(vb.imCovert);
        vb.tvTitle.setText(boxLikeSong.getSongName());
        vb.tvSingerName.setText(boxLikeSong.getSingerName());

        vb.getRoot().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (homeItemClickListener != null) {
                    int absoluteAdapterPosition = itemHolder.getAbsoluteAdapterPosition();
                    homeItemClickListener.onClickLikeSong(boxLikeSong, absoluteAdapterPosition);
                }
            }
        });

    }


}
