package com.hainaos.vc.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.recyclerview.widget.RecyclerView;

import com.arialyy.annotations.Download;
import com.arialyy.aria.core.Aria;
import com.arialyy.aria.core.task.DownloadTask;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hainaos.vc.CustomJzvd.JzvdStdAssert;
import com.hainaos.vc.R;
import com.hainaos.vc.bean.LocalVideoInfo;
import com.hainaos.vc.gson.GsonUtils;
import com.hainaos.vc.utils.JgyUtils;
import com.hainaos.vc.utils.SPUtils;
import com.hainaos.vc.utils.VideoUtils;
import com.shehuan.niv.NiceImageView;

import java.lang.reflect.Type;
import java.util.List;

import cn.jzvd.JZDataSource;
import cn.jzvd.Jzvd;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableOnSubscribe;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;
import wseemann.media.FFmpegMediaMetadataRetriever;

public class TikTokRecyclerViewAdapter extends RecyclerView.Adapter<TikTokRecyclerViewAdapter.MyViewHolder> {

    public static final String TAG = "AdapterTikTokRecyclerView";
    private List<LocalVideoInfo> videoPath;
    private Context context;
    private onVideoCompletListener completListener;
    private onOrientationChangeListener onOrientationChangeListener;
    private onGotoFullScreenListener gotoFullScreenListener;

    public TikTokRecyclerViewAdapter(Context context) {
        this.context = context;
    }

    public TikTokRecyclerViewAdapter(Context context, List<LocalVideoInfo> list) {
        this.context = context;
        this.videoPath = list;
    }

    public void setVideoCompletListener(onVideoCompletListener listener) {
        this.completListener = listener;
    }

    public interface onVideoCompletListener {
        void onVideoComplet();
    }

    public void setOrientationChangeListener(onOrientationChangeListener listener) {
        this.onOrientationChangeListener = listener;
    }

    public void setGotoFullScreenListener(onGotoFullScreenListener listener) {
        this.gotoFullScreenListener = listener;
    }

    public interface onOrientationChangeListener {
        void onOrientationChange();
    }

    public interface onGotoFullScreenListener {
        void gotoFullScreen();
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        MyViewHolder holder = new MyViewHolder(LayoutInflater.from(
                context).inflate(R.layout.item_tiktok, parent,
                false));
        Aria.download(this).register();
        return holder;
    }

    @SuppressLint("LongLogTag")
    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        Log.i(TAG, "onBindViewHolder [" + holder.jzvdStdAssert.hashCode() + "] position=" + position);
        LocalVideoInfo localVideoInfo = videoPath.get(position);
        String localPath = localVideoInfo.getLocalPath();
        if (TextUtils.isEmpty(localPath)) {
            holder.jzvdStdAssert.setVisibility(View.GONE);
            holder.ivStatus.setVisibility(View.VISIBLE);
            holder.iv_cover.setVisibility(View.VISIBLE);
            String url = localVideoInfo.getFile();
            String path = JgyUtils.getInstance().getUrlLocalPath(url);
            Log.e(TAG, "onBindViewHolder: getUrlLocalPath: " + path);
            JZDataSource jzDataSource = new JZDataSource(path, VideoUtils.getFileNameWithoutExtension(path));
            int singleLoop = (int) SPUtils.get(context, "single_loop", 0);
            jzDataSource.looping = (singleLoop == 1);
            holder.jzvdStdAssert.setUp(jzDataSource, Jzvd.SCREEN_NORMAL);
            Glide.with(holder.iv_cover).load(url).error(R.mipmap.ic_launcher).into(holder.iv_cover);
            holder.ivStatus.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    JgyUtils.getInstance().ariaDownload(url, GsonUtils.getJsonObject(GsonUtils.toJSONString(localVideoInfo)));
                }
            });
        } else {
            holder.jzvdStdAssert.setVisibility(View.VISIBLE);
            holder.ivStatus.setVisibility(View.GONE);
            holder.iv_cover.setVisibility(View.GONE);
            JZDataSource jzDataSource = new JZDataSource(localPath, VideoUtils.getFileNameWithoutExtension(localPath));
            int singleLoop = (int) SPUtils.get(context, "single_loop", 0);
            jzDataSource.looping = (singleLoop == 1);
            holder.jzvdStdAssert.setUp(jzDataSource, Jzvd.SCREEN_NORMAL);
            Observable.create((ObservableOnSubscribe<Bitmap>) emitter -> {
                FFmpegMediaMetadataRetriever mmr = new FFmpegMediaMetadataRetriever();
                mmr.setDataSource(localPath);
                Bitmap bitmap = mmr.getFrameAtTime();//获得视频第一帧的Bitmap对象.
                mmr.release();
                emitter.onNext(bitmap);
            }).subscribeOn(Schedulers.newThread())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<Bitmap>() {
                        @Override
                        public void onSubscribe(Disposable d) {

                        }

                        @Override
                        public void onNext(Bitmap bitmap) {
                            try {
                                holder.jzvdStdAssert.posterImageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
                                Glide.with(holder.jzvdStdAssert.posterImageView).load(bitmap).into(holder.jzvdStdAssert.posterImageView);
                            } catch (Exception e) {

                            }
                        }

                        @Override
                        public void onError(Throwable e) {

                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        }
        holder.jzvdStdAssert.setOnCompletionListener(() -> {
            completListener.onVideoComplet();
        });
        holder.jzvdStdAssert.setScreenOrientationChangeListener(new JzvdStdAssert.ScreenOrientationChangeListener() {
            @Override
            public void onOrientationChange() {
                onOrientationChangeListener.onOrientationChange();
            }
        });
        holder.jzvdStdAssert.setGotoFullScreenListener(new JzvdStdAssert.GotoFullScreenListener() {
            @Override
            public void onGotoFullScreen() {
                gotoFullScreenListener.gotoFullScreen();
            }
        });
    }

    @Override
    public int getItemCount() {
        return videoPath == null ? 0 : videoPath.size();
    }

    class MyViewHolder extends RecyclerView.ViewHolder {
        JzvdStdAssert jzvdStdAssert;
        NiceImageView ivStatus;
        ImageView iv_cover;

        public MyViewHolder(View itemView) {
            super(itemView);
            jzvdStdAssert = itemView.findViewById(R.id.videoplayer);
            ivStatus = itemView.findViewById(R.id.iv_status);
            iv_cover = itemView.findViewById(R.id.iv_cover);
        }
    }

    @Download.onTaskComplete
    void taskComplete(DownloadTask task) {
        //在这里处理任务完成的状态
        Log.e("taskComplete", task.getFilePath());
        Log.e("taskComplete", task.getExtendField());
        if (videoPath == null || videoPath.size() == 0) {
            return;
        }
        String jsonString = task.getExtendField();
        Gson gson = new Gson();
        Type type = new TypeToken<LocalVideoInfo>() {
        }.getType();
        try {
            LocalVideoInfo localVideoInfo = gson.fromJson(jsonString, type);
            for (int i = 0; i < videoPath.size(); i++) {
                if (localVideoInfo.getFile().equals(videoPath.get(i).getFile())) {
                    videoPath.get(i).setLocalPath(task.getFilePath());
                    this.notifyItemChanged(i);
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "taskComplete: " + e.getMessage());
        }


    }

}
