package com.efounder.chat.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.FutureTarget;
import com.efounder.chat.R;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.model.Group;
import com.efounder.mobilecomps.contacts.User;
import com.groupimageview.NineGridImageView;
import com.groupimageview.NineGridImageViewAdapter;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * group群组头像生成的类 2016.12.21
 * Created by cherise on 2016/9/7.
 */

public class GroupAvatarHelper {
    private final String TAG = "GroupAvatarHelper";

//    private ImageLoader imageLoader;
//    private DisplayImageOptions options;
    private Context context;

    public GroupAvatarHelper(Context context) {
        this.context = context;
//        imageLoader = ImageLoader.getInstance();
//        options = ImageUtil.getImageLoaderOptions(R.drawable.default_useravatar);

    }

    /**
     * 根据群组id创建群头像
     *
     * @param groupId
     */
    public void createNewGroupAvatar(int groupId) {
        if (HttpRequestStatusUtils.isRequest(groupId + "", HttpRequestStatusUtils.AVATAR_TYPE)) {
            return;
        }
        HttpRequestStatusUtils.add(groupId + "", HttpRequestStatusUtils.AVATAR_TYPE);
        Log.i(TAG, "---createNewGroupAvatar生成新的群组头像----");
        Group tempGroup = WeChatDBManager.getInstance().getGroupWithUsers(groupId);
        if (tempGroup == null) {

            return;
        }
        //如果群头像是网络图片就不自动生成了
        if (GroupAvatarUtil.isServerAvatar(tempGroup.getAvatar())) {
            Log.i(TAG, "---createNewGroupAvatar网络头像，停止生成----");
            HttpRequestStatusUtils.remove(groupId + "", HttpRequestStatusUtils.AVATAR_TYPE);
            return;
        }
        //如果群成员数大于12，并且头像已生成并且存在，也无需再次生成
        if (tempGroup.getUsers() != null && tempGroup.getUsers().size() >= 10) {
            File file = new File(tempGroup.getAvatar());
            if (file.exists()) {
                Log.i(TAG, "---头像已存在，停止生成----");
                HttpRequestStatusUtils.remove(groupId + "", HttpRequestStatusUtils.AVATAR_TYPE);
                return;
            }

        }
        List<String> list = new ArrayList<>();
        if (tempGroup.getUsers() != null) {
            for (User user : tempGroup.getUsers()) {
                list.add(user.getAvatar());
            }
            Log.i(TAG, "yqs当前群组中的人数:" + list.size());
            getAvatar(tempGroup, list, null);
        }else{
            HttpRequestStatusUtils.remove(groupId + "", HttpRequestStatusUtils.AVATAR_TYPE);
        }
    }

    /**
     * 传入头像数组，得到头像
     *
     * @param urlList
     * @param loadImageListener
     */

    public void getAvatar(final Group group, final List<String> urlList, final LoadImageListener loadImageListener) {
        if (urlList.size() <= 1) {
            if (loadImageListener != null) {
                loadImageListener.loadImageComplete(null);
            }
            HttpRequestStatusUtils.remove(group.getGroupId() + "", HttpRequestStatusUtils.AVATAR_TYPE);
            return;
        }
        //线程中处理群组头像，请求头像需要在线程中执行
        //new Thread(new MyRunnnable(urlList,group,loadImageListener)).start();
        CommonThreadPoolUtils.execute(new MyRunnnable(urlList, group, loadImageListener));
    }

    public class MyRunnnable implements Runnable {
        int i = 0;
        private List<String> urlList;
        private Group group;
        private LoadImageListener loadImageListener;

        public MyRunnnable(List<String> urlList, Group group, LoadImageListener loadImageListener) {
            this.urlList = urlList;
            this.group = group;
            this.loadImageListener = loadImageListener;
        }

        @Override
        public void run() {
            synchronized (Group.class) {
                Log.i("-----", "线程：" + Thread.currentThread() + "，生成群头像-----开始");
                final int max = urlList.size() >= 9 ? 9 : urlList.size();
                final NineGridImageView nineGridImageView = new NineGridImageView(context);
                final NineGridImageViewAdapter<String> mAdapter = new NineGridImageViewAdapter<String>() {
                    @Override
                    protected void onDisplayImage(final Context context, ImageView imageView, String s) {
                        Log.i("-----", "线程：" + Thread.currentThread() + "，生成群头像-----onDisplayImage");
                        Object tempObject = s;
                        if (s == null || "".equals(s) ||s.startsWith("http://panserver.solarsource.cn:9692/panserver")
                                ||s.startsWith("https://panserver.solarsource.cn/panserver")
                        ) {
                            tempObject= R.drawable.default_useravatar;
                        }
                        try {
                            //Bitmap bitmap = imageLoader.loadImageSync(s, options);
                            //imageView.setImageBitmap(bitmap);
                            FutureTarget<Drawable> target = Glide.with(context)
                                    .load(tempObject)
//                                    .submit(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL);
                                    .submit(150, 150);
                            final Drawable imageDrawable = target.get();
                            imageView.setImageDrawable(imageDrawable);

                            i += 1;
                            if (i == max) {
                                if (loadImageListener != null) {
                                    loadImageListener.loadImageComplete(nineGridImageView);
                                } else {
                                    String path = getAvatarPath(nineGridImageView);
                                    group.setAvatar(path);
                                    WeChatDBManager.getInstance().insertOrUpdateGroup(group);

                                }
                                HttpRequestStatusUtils.remove(group.getGroupId() + "", HttpRequestStatusUtils.AVATAR_TYPE);
                            }
                        } catch (Exception e) {
                            HttpRequestStatusUtils.remove(group.getGroupId() + "", HttpRequestStatusUtils.AVATAR_TYPE);
                            e.printStackTrace();
                        }
                    }

                    @Override
                    protected ImageView generateImageView(Context context) {
                        return super.generateImageView(context);
                    }
                };

                nineGridImageView.setAdapter(mAdapter);
                nineGridImageView.setImagesData(urlList);
                getBmFromView(nineGridImageView);
            }

        }
    }

    public String getAvatarPath(NineGridImageView view) {
        Bitmap bitmap = getBmFromView(view);
        String filePath = viewSaveToImage(bitmap);
        Log.i(TAG, "线程：" + Thread.currentThread() + "，生成的头像路径" + filePath);
        return filePath;
    }

    /**
     * 从View中得到bitmap
     *
     * @param view
     * @return
     */
    public Bitmap getBmFromView(NineGridImageView view) {
        if (view == null) {
            return null;
        }
        view.setDrawingCacheEnabled(true);
        view.measure(
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        view.layout(0, 0, view.getMeasuredWidth(),
                view.getMeasuredHeight());
        view.buildDrawingCache();
        Bitmap bitmap = Bitmap.createBitmap(view.getParentWidth(), view.getParentHeight(), Bitmap.Config.ARGB_8888);
        view.draw(new Canvas(bitmap));
        view.destroyDrawingCache();

        //  Log.i("-----", "线程：" + Thread.currentThread() + "生成群头像-----结束");
        return bitmap;

    }

    /**
     * 保存bitmao返回文件路径
     *
     * @param bitmap
     * @return
     */
    public String viewSaveToImage(Bitmap bitmap) {
        File file = null;
        if (bitmap == null) {
            return null;
        }

        FileOutputStream fos;
        try {
            // 判断手机设备是否有SD卡
            boolean isHasSDCard = Environment.getExternalStorageState().equals(
                    Environment.MEDIA_MOUNTED);
            if (isHasSDCard) {

                File root = new File(ImageUtil.chatpath);
                if (!root.exists()) {
                    root.mkdirs();
                }
                file = new File(root, getNowTime());
                System.out.printf(file.getName());
                fos = new FileOutputStream(file);
            } else
                throw new Exception("创建文件失败!");

            bitmap.compress(Bitmap.CompressFormat.PNG, 10, fos);

            fos.flush();
            fos.close();

        } catch (Exception e) {
            e.printStackTrace();
        }


        if (file!=null && file.exists()) {
            return file.getPath();
        } else {
            return null;
        }
    }

    private String getNowTime() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyMMddHHmmssSS");
        return dateFormat.format(date);
    }

    public interface LoadImageListener {
        public void loadImageComplete(NineGridImageView view);
    }

}
