package com.hainaos.vc.adapter;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.os.AsyncTask;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.JsonParser;
import com.hainaos.vc.R;
import com.hainaos.vc.activity.tiktok.TikTokActivity;
import com.hainaos.vc.bean.LocalVideoInfo;
import com.hainaos.vc.gson.GsonUtils;
import com.hainaos.vc.utils.JgyUtils;
import com.hainaos.vc.utils.TimeUtils;
import com.hainaos.vc.utils.ToastUtil;
import com.hainaos.vc.utils.VideoUtils;
import com.shehuan.niv.NiceImageView;

import java.io.File;
import java.util.ArrayList;

public class VideoAdapter extends RecyclerView.Adapter<VideoAdapter.VideoHolder> {
    private static final String TAG = "VideoAdapter";
    private Activity mContext;
    private ArrayList<LocalVideoInfo> mLocalVideoInfos;
    private onItemLongClickListener onItemLongClickListener;

    public VideoAdapter() {

    }

    public VideoAdapter(Activity context) {
        this.mContext = context;
    }

    public VideoAdapter(Activity context, ArrayList<LocalVideoInfo> path) {
        this.mContext = context;
        this.mLocalVideoInfos = path;
    }

    private static class VideoResult {
        long time;
        Bitmap frame;

        @NonNull
        @Override
        public String toString() {
            return JsonParser.parseString(new Gson().toJson(this)).getAsJsonObject().toString();
        }
    }

    public void setData(ArrayList<LocalVideoInfo> paths) {
        this.mLocalVideoInfos = paths;
        notifyDataSetChanged();
    }

    public void setOnLongClickListener(onItemLongClickListener listener) {
        this.onItemLongClickListener = listener;
    }

    @NonNull
    @Override
    public VideoHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        VideoHolder holder = new VideoHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_videofile, parent, false));
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull final VideoHolder holder, final int position) {
        LocalVideoInfo localVideoInfo = mLocalVideoInfos.get(position);
        final String localPath = localVideoInfo.getLocalPath();
        String url = localVideoInfo.getFile();
        Log.e(TAG, "onBindViewHolder: " + localPath);
        if (TextUtils.isEmpty(localPath)) {
            holder.iv_status.setVisibility(View.VISIBLE);
            if (!TextUtils.isEmpty(url)) {
                Glide.with(mContext).load(url + "?x-oss-process=video/snapshot,t_0,f_jpg").error(R.mipmap.ic_launcher).into(holder.video_image);
                String fileName = localVideoInfo.getFile_name();
                if (TextUtils.isEmpty(fileName)) {
                    holder.title.setText(VideoUtils.getFileNameWithoutExtension(url));
                } else {
                    holder.title.setText(fileName);
                }
                holder.duration.setText(TimeUtils.TimeFormat(localVideoInfo.getDuration() * 1000));
            }
        } else {
            holder.title.setText(VideoUtils.getFileNameWithoutExtension(localPath));
            File file = new File(localPath);
            if (file.exists()) {
                holder.iv_status.setVisibility(View.GONE);
                Glide.with(mContext).load(url + "?x-oss-process=video/snapshot,t_0,f_jpg").error(R.mipmap.ic_launcher).into(holder.video_image);
                holder.duration.setText(TimeUtils.TimeFormat(localVideoInfo.getDuration() * 1000));
//                Observable.create(new ObservableOnSubscribe<VideoResult>() {
//                    @Override
//                    public void subscribe(ObservableEmitter<VideoResult> emitter) throws Exception {
//                        FFmpegMediaMetadataRetriever mmr = new FFmpegMediaMetadataRetriever();
//                        mmr.setDataSource(localPath);
//                        String duration = mmr.extractMetadata(FFmpegMediaMetadataRetriever.METADATA_KEY_DURATION);
//                        Bitmap bitmap = mmr.getFrameAtTime();//获得视频第一帧的Bitmap对象.
//                        Long time = Long.valueOf(duration);
//
//                        mmr.release();
//                        VideoResult result = new VideoResult();
//                        result.frame = bitmap;
//                        result.time = time;
//                        emitter.onNext(result);
//                    }
//                }).subscribeOn(Schedulers.newThread())
//                        .observeOn(AndroidSchedulers.mainThread())
//                        .subscribe(new Observer<VideoResult>() {
//                            @Override
//                            public void onSubscribe(Disposable d) {
//                                Log.e("VideoResult", "onSubscribe: ");
//                            }
//
//                            @Override
//                            public void onNext(VideoResult result) {
//                                Log.e("VideoResult", "onNext: " + result);
//                                try {
//                                    Glide.with(holder.video_image).load(result.frame).skipMemoryCache(false).into(new SimpleTarget<Drawable>() {
//                                        @Override
//                                        public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
//                                            holder.video_image.setImageDrawable(resource);
//                                        }
//                                    });
//                                    holder.duration.setText(Utils.TimeFormat(result.time));
//                                } catch (Exception e) {
//
//                                }
//                            }
//
//                            @Override
//                            public void onError(Throwable e) {
//                                Log.e("VideoResult", "onError: " + e.getMessage());
//                            }
//
//                            @Override
//                            public void onComplete() {
//                                Log.e("VideoResult", "onComplete: ");
//                            }
//                        });
            } else {
                holder.iv_status.setVisibility(View.VISIBLE);

            }
        }

        holder.iv_status.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(localPath)) {
                    if (JgyUtils.getInstance().fileExists(url)) {
                        Intent intent = new Intent(mContext, TikTokActivity.class);
                        intent.putExtra("position", position);
                        intent.putParcelableArrayListExtra("list", mLocalVideoInfos);
                        mContext.startActivity(intent);
                    } else {
                        JgyUtils.getInstance().ariaDownload(url, GsonUtils.getJsonObject(GsonUtils.toJSONString(localVideoInfo)));
                        ToastUtil.show(String.format(mContext.getString(R.string.download_now), VideoUtils.getFileNameWithoutExtension(url)));
                    }
                } else {
                    Intent intent = new Intent(mContext, TikTokActivity.class);
                    intent.putExtra("position", position);
                    intent.putParcelableArrayListExtra("list", mLocalVideoInfos);
                    mContext.startActivity(intent);
                }
            }
        });
        Log.e("title:", holder.title.getText().toString());
//        }
        holder.root.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (TextUtils.isEmpty(localPath)) {
                    if (JgyUtils.getInstance().fileExists(url)) {
                        Intent intent = new Intent(mContext, TikTokActivity.class);
                        intent.putExtra("position", position);
                        intent.putParcelableArrayListExtra("list", mLocalVideoInfos);
                        mContext.startActivity(intent);
                    } else {
                        JgyUtils.getInstance().ariaDownload(url, GsonUtils.getJsonObject(GsonUtils.toJSONString(localVideoInfo)));
                        ToastUtil.show(String.format(mContext.getString(R.string.download_now), VideoUtils.getFileNameWithoutExtension(url)));
                    }
                } else {
                    Intent intent = new Intent(mContext, TikTokActivity.class);
                    intent.putExtra("position", position);
                    intent.putParcelableArrayListExtra("list", mLocalVideoInfos);
                    mContext.startActivity(intent);
                }
            }
        });
        holder.root.setOnLongClickListener(view -> {
            onItemLongClickListener.onItemLongClick(localPath, position);
            return false;
        });
    }

    public interface onItemLongClickListener {
        void onItemLongClick(String path, int position);
    }

    public void removeItem(int position) {
        if (null != mLocalVideoInfos.get(position)) {
            mLocalVideoInfos.remove(position);
        }
        notifyDataSetChanged();
    }

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


    @Override
    public int getItemViewType(int position) {
        return position;
    }

    public static boolean isDestroy(Activity mActivity) {
        if (mActivity == null || mActivity.isFinishing() || (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && mActivity.isDestroyed())) {
            return true;
        } else {
            return false;
        }
    }

    static class VideoHolder extends RecyclerView.ViewHolder {
        NiceImageView video_image, iv_status;
        TextView title, duration;
        ConstraintLayout root;

        public VideoHolder(@NonNull View itemView) {
            super(itemView);
            video_image = itemView.findViewById(R.id.video_image);
            iv_status = itemView.findViewById(R.id.iv_status);
            title = itemView.findViewById(R.id.title_text);
            duration = itemView.findViewById(R.id.duration);
            root = itemView.findViewById(R.id.root);
        }

    }

    private BitmapRetultListener listener;

    class BitmapTask extends AsyncTask<String, Void, Bitmap> {
        @Override
        protected Bitmap doInBackground(String... strings) {
            MediaMetadataRetriever mmr = new MediaMetadataRetriever();
            mmr.setDataSource(strings[0]);
            Bitmap bitmap = mmr.getFrameAtTime();//获得视频第一帧的Bitmap对象
            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            listener.onScanCompleted(bitmap);
        }

    }


    interface BitmapRetultListener {
        void onScanCompleted(Bitmap bitmap);
    }

}
