package com.efounder.chat.item;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.MultiTransformation;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.request.RequestOptions;
import com.efounder.chat.R;
import com.efounder.chat.activity.PlayerActivity;
import com.efounder.chat.item.manager.IMessageItem;
import com.efounder.chat.model.AppConstant;
import com.efounder.chat.utils.ImageUtil;
import com.efounder.chat.view.SendImgProgressView;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.ViewSize;
import com.efounder.frame.utils.Constants;
import com.efounder.message.struct.IMStruct002;
import com.efounder.util.AppContext;
import com.efounder.util.JSONUtil;
import com.google.gson.JsonPrimitive;

import java.io.File;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import jp.wasabeef.glide.transformations.RoundedCornersTransformation;

import static com.efounder.frame.utils.Constants.CHAT_USER_ID;

/**
 * @author lch 视频
 */
public class VideoMessageItem extends RelativeLayout implements IMessageItem,
        View.OnClickListener {
    private static final String TAG = "VideoMessageItem";

    private Context mContext;
    private ImageView mVideoCover;
    private LinearLayout imgStartBgLl;
    // private ProgressView progressView;
    private SendImgProgressView progressView;//显示发送进度

    private ViewGroup video_item;

    private IMStruct002 imStruct002;
    private MultiTransformation multi;
    private LoadBitmapAsyncTask loadBitmapAsyncTask;

//	private Bitmap mBitmap;//每个view中持有一个bitmap（如果放到imSruct中，会内存占用过多）


    public VideoMessageItem(Context context) {
        super(context);
        mContext = context;
        initView(context);
        multi = new MultiTransformation(
                new CenterCrop(),
                new RoundedCornersTransformation(10, 0,
                        RoundedCornersTransformation.CornerType.ALL));
    }

    private void initView(Context context) {
        LayoutInflater inflater = LayoutInflater.from(context);
        video_item = (ViewGroup) inflater.inflate(R.layout.activity_pl_video_view, this);
        imgStartBgLl = (LinearLayout) video_item.findViewById(R.id.video_cover_start);//播放图标
        mVideoCover = (ImageView) video_item.findViewById(R.id.video_cover_1);//显示预览图
        progressView = (SendImgProgressView) video_item.findViewById(R.id.progressView);//上传进度
        mVideoCover.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.video_cover_1) {
            String pathOrUrl = getPathOrUrl(imStruct002);
            String videoName = getVideoName(imStruct002);
            Intent intent;
            if (pathOrUrl.startsWith("/storage")) {
//                intent = new Intent(getContext(), NewWindowVideoPlayActivity.class);
//                intent.putExtra("videoPath", pathOrUrl);

                intent = new Intent(getContext(), PlayerActivity.class);
                intent.putExtra("localFilePath", pathOrUrl);
            } else {
                //网络路径
                intent = new Intent(getContext(), PlayerActivity.class);
                intent.putExtra("videoPath", pathOrUrl);
                intent.putExtra("videoName", videoName);
            }
            mContext.startActivity(intent);
        }
    }

    @Override
    public View messageView() {
        return this;
    }

    @Override
    public ViewSize messageViewSize() {
        return null;
    }

    @Override
    public void setIMStruct002(IMStruct002 message) {
        imStruct002 = message;
        dataChanged(message);
    }

    private void dataChanged(IMStruct002 imStruct002) {
        //判断是否是发送的,如果是,则加载本地路径
        if (imStruct002.getFromUserId() == Integer.valueOf(EnvironmentVariable.getProperty(Constants.CHAT_USER_ID))) {
//            展示小视频
            if (imStruct002.getExtra("progress") == null) {
                showThumbnail(imStruct002);
            } else {
                mVideoCover.setVisibility(View.VISIBLE);
                imgStartBgLl.setVisibility(View.VISIBLE);
                showThumbnail(imStruct002);

                Object object = imStruct002.getExtra("progress");
                if ((object instanceof JsonPrimitive && ((JsonPrimitive) object)
                        .getAsInt() == -1) || (object instanceof Integer && (int) object == -1)) {
                    //progress为-1，说明发送失败，隐藏进度条
                    progressView.setVisibility(View.GONE);
                } else {
                    //本地预发送图片的view
                    progressView.setVisibility(View.VISIBLE);
                    int progress = 0;
                    if ((object instanceof JsonPrimitive)) {
                        progress = ((JsonPrimitive) object).getAsInt();
                    } else {
                        progress = (int) object;
                    }
                    progressView.setProgress(progress);
                    if (progress == 100) {
                        progressView.setVisibility(View.GONE);
                        imgStartBgLl.setVisibility(View.VISIBLE);
                    }
                }
            }
        } else {//收到的消息
            showThumbnail(imStruct002);
        }
    }

    private String getPathOrUrl(IMStruct002 imStruct002) {
        //判断是否是JSON数据,没有"url"的话为以前的消息结构
        if (!imStruct002.getMessage().contains("url")) {
            String url = imStruct002.getMessage();
            return url;
        }
        if (imStruct002.getFromUserId() == Integer.valueOf(EnvironmentVariable.getProperty(Constants.CHAT_USER_ID))) {//发送的消息
            String path = JSONUtil.parseJson(imStruct002.getMessage()).get("path").getAsString();
            if (new File(path).exists()) {//发送的消息本地文件是否存在（多设备登录，某设备会没有本地文件）
                return path;
            } else {//本地文件不存在，返回url
                return JSONUtil.parseJson(imStruct002.getMessage()).get("url").getAsString();
            }
        } else {
            return JSONUtil.parseJson(imStruct002.getMessage()).get("url").getAsString();
        }
    }


    /**
     * videoName 取的是本地文件路径的文件名
     *
     * @param imStruct002
     * @return
     */
    private String getVideoName(IMStruct002 imStruct002) {
        String path = JSONUtil.parseJson(imStruct002.getMessage()).get("path").getAsString();
        String videoName = path.substring(path.lastIndexOf("/") + 1, path.length());
        return videoName;
    }

    public void showThumbnail(final IMStruct002 imStruct002) {

        //todo 使用glide 加载,屏蔽之前的方法
//        String localFilePath = ImageUtil.videopath + getVideoName(imStruct002);
       // if (new File(localFilePath).exists()) {
            Glide.with(getContext()).load(getPathOrUrl(imStruct002))
                    .apply(new RequestOptions()
                            .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .transform(multi))
                    .into(mVideoCover);
//        }else{
//
//            Glide.with(getContext()).load(localFilePath)
//                    .apply(new RequestOptions()
//                            .diskCacheStrategy(DiskCacheStrategy.ALL))
//                    .into(mVideoCover);
//        }


        if (true) {
            return;
        }


        //ImageLoader可以加载本地的，不能加载网络的
//		ImageLoader.getInstance().displayImage("file://" + getPathOrUrl(imStruct002),mVideoCover);
        mVideoCover.setTag(R.id.glide_imageview_id, imStruct002);
        //1.从内存中获取bitmap
        Bitmap bitmap = BitmapPool.get(imStruct002.getMessageID());
        String path = getPathOrUrl(imStruct002);
        String filepath = AppConstant.APP_ROOT + "/" + EnvironmentVariable.getProperty(CHAT_USER_ID) + "/chat/chatvideo/" + getVideoName(imStruct002);
        if (bitmap != null) {
            setThumbnail(bitmap);
        } else if ((new File(filepath).exists() && filepath.endsWith(".mp4")) || path.startsWith("/")) {
//            判断是否下载到本地或发的视频
            if (path.startsWith("/")) {
                filepath = path;
            }
            if (mVideoCover.getTag(R.id.glide_imageview_id).equals(VideoMessageItem.this.imStruct002))
                //   LXGlideImageLoader.getInstance().displayImage(mContext,mVideoCover,"file://" + filepath);
                Glide.with(mContext).load("file://" + filepath)
                        .apply(new RequestOptions()
                                // .bitmapTransform(new RoundedCornersTransformation(10, 0))
                                .transform(multi)
                                .diskCacheStrategy(DiskCacheStrategy.ALL))
                        .into(mVideoCover);
//

//            Glide.with(mContext).load("file://" + filepath).into(mVideoCover);
        } else {//2.从缓存的缩略图，或者视频中（本地，或网络）取bitmap
            boolean isCreateThumbnailThreadRunning = BitmapPool.isCreateThumbnailThreadRunning(imStruct002.getMessageID());
            if (!isCreateThumbnailThreadRunning) {//如果创建缩略图的线程没有正在运行，新建线程获取缩略图（避免开启多个线程）
                BitmapPool.setIsCreateThumbnailThreadRunning(imStruct002.getMessageID(), true);//1.标记线程正在运行
//                new LoadBitmapAsyncTask(imStruct002).executeOnExecutor(Executors.newCachedThreadPool());//AsyncTask.THREAD_POOL_EXECUTOR

                loadBitmapAsyncTask = new LoadBitmapAsyncTask(mVideoCover, imStruct002);
                loadBitmapAsyncTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);//AsyncTask.THREAD_POOL_EXECUTOR
            }
        }

//        int width = DisplayUtil.getMobileWidth(mContext) * 2 / 3 - 40;
//        System.out.println("最大宽度" + width);
//
//        RelativeLayout.LayoutParams lp = new LayoutParams(
//                width, width * 3 / 4);
//        this.setLayoutParams(lp);
    }

    private void setThumbnail(Bitmap bitmap) {
        if (bitmap == null) {
            mVideoCover.setBackgroundDrawable(null);
        } else {
            BitmapDrawable drawable = new BitmapDrawable(bitmap);
            drawable.setDither(true);
            mVideoCover.setBackgroundDrawable(drawable);
        }
    }

    @Override
    public boolean getIsInUse() {
        return this.isShown();
    }

    @Override
    public void setIsInUse(boolean isInUse) {
    }

    @Override
    public void prepareForReuse() {
        progressView.setVisibility(View.GONE);
        mVideoCover.setBackgroundDrawable(null);
    }

    public static class BitmapPool {
        private static final int MAX_SIZE = 20;
        private static LinkedHashMap<String, Bitmap> bitmapPool = new LinkedHashMap<>(MAX_SIZE);
        //是否线程中正在生成缩略图，如果线程中正在生成缩略图，不再开启线程取bitmap
        private static Map<String, Boolean> isCreateThumbnailThreadRunningMap = new HashMap<>();

        private static synchronized void putBitmapInPool(String key, Bitmap bitmap) {
            if (bitmapPool.size() >= MAX_SIZE) {
                String firstKey = bitmapPool.keySet().iterator().next();
                bitmapPool.remove(firstKey);
            }
            bitmapPool.put(key, bitmap);
        }

        private static Bitmap get(String key) {
            return bitmapPool.get(key);
        }

        private static boolean isCreateThumbnailThreadRunning(String key) {
            Boolean bool = isCreateThumbnailThreadRunningMap.get(key);
            return bool == null ? false : bool;
        }

        private static void setIsCreateThumbnailThreadRunning(String key, boolean isCreateThumbnailThreadRunning) {
            isCreateThumbnailThreadRunningMap.put(key, isCreateThumbnailThreadRunning);
        }

        public static void release() {
            bitmapPool.clear();
            isCreateThumbnailThreadRunningMap.clear();
        }

    }

    private class LoadBitmapAsyncTask extends AsyncTask<String, Integer, Bitmap> {
        private ImageView iv;
        private IMStruct002 imStruct002;

        public LoadBitmapAsyncTask(ImageView iv, IMStruct002 imStruct002) {
            super();
            this.imStruct002 = imStruct002;
            this.iv = iv;
        }

        @Override
        protected Bitmap doInBackground(String... params) {
            Bitmap bitmap = null;
            //1.判断是否存在缓存的缩略图,如果存在，直接返回bitmap
            String absolutePath = AppContext.getInstance().getCacheDir().getAbsolutePath();
            String videoName = getVideoName(imStruct002);
            String vName = videoName.substring(0, videoName.lastIndexOf("."));
            if (new File(absolutePath + File.separator + "cache_thumbnail/" + vName.hashCode()).exists()) {
                bitmap = ImageUtil.getCacheVideoThumbnail(vName);
                return bitmap;
            }
            String path = getPathOrUrl(imStruct002);
            // 通过路径获取第一帧的缩略图并显示
//            if (path.startsWith("http")) {
//                String filepath = AppConstant.APP_ROOT + "/" + EnvironmentVariable.getProperty(CHAT_USER_ID) + "/chat/chatvideo/" + videoName;
//                if (new File(filepath).exists()) {
//                    String prePath = filepath.substring(0, filepath.lastIndexOf("/"));
//                    bitmap = ImageUtil.getVideoThumbnail(prePath, videoName);
//                } else {
            bitmap = ImageUtil.getVideoThumbnail(path, 500, 300);
//                }
//                if (bitmap != null)
//                    ImageUtil.saveCacheVideoThumbnail(bitmap, vName);
//            } else if (path.startsWith("/")) {
//                String filePath = path.substring(0, path.lastIndexOf("/"));
//                String fileName = getFileName(imStruct002);
//                bitmap = ImageUtil.getVideoThumbnail(filePath, fileName);
//            }
            if (bitmap != null)
                ImageUtil.saveCacheVideoThumbnail(bitmap, vName);
            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            BitmapPool.putBitmapInPool(imStruct002.getMessageID(), bitmap);
            if (mVideoCover.getTag(R.id.glide_imageview_id) == VideoMessageItem.this.imStruct002 && null != bitmap) {//如果View中数据数据还是原来的数据
//                setThumbnail(bitmap);

                // iv.setImageBitmap(bitmap);
                if (mContext == null) {
                    return;
                }
                if (((Activity) mContext).isDestroyed()) {
                    return;
                }
                Glide.with(mContext).load(bitmap)
                        .apply(new RequestOptions()
                                //.bitmapTransform(new RoundedCornersTransformation(10, 0))
                                .transform(multi)
                                .diskCacheStrategy(DiskCacheStrategy.ALL))
                        .into(iv);

            }
            BitmapPool.setIsCreateThumbnailThreadRunning(imStruct002.getMessageID(), false);//2.标记线程运行结束
        }


    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (loadBitmapAsyncTask != null) {
            loadBitmapAsyncTask.cancel(true);
            loadBitmapAsyncTask = null;
        }
    }
}
