package com.efounder.pansoft.chat.animation;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.NinePatch;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.NinePatchDrawable;

import com.efounder.chat.model.AppConstant;
import com.efounder.chat.utils.JFChatStyleManager;
import com.utilcode.util.FileUtils;

import net.sf.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 管理聊天头像 气泡 帧动画读取
 */
public class ChatStyleFactory {

    public static Map<String, Drawable> animMap = new HashMap<>();
    //默认
    public static final int DEFAULT_PATTERN = 0;
    //收消息
    public static final int DEFAULT_MESSAGE_INCOMEING = 1;
    //发消息
    public static final int DEFAULT_MESSAGE_OUT = 2;

    //头像挂件存放路径
    public static String avatarHangPath = AppConstant.APP_ROOT + "/res/unzip_res/Image/common/.avatar";
    //气泡存放路径
    public static String bubblePath = AppConstant.APP_ROOT + "/res/unzip_res/Image/common/.bubble";
    //emoji存放路径
    public static String emojiPath = AppConstant.APP_ROOT + "/res/unzip_res/Image/common/.emoji";
    //动画存放路径
    public static String animationPath = AppConstant.APP_ROOT + "/res/unzip_res/Image/common/.animation";


    public static Drawable getAnimation(String key, Object value) {
        return getAnimation(key, value, DEFAULT_PATTERN);
    }

    public static Drawable getAnimation(String key, Object value, int pattern) {
        try {
            if (JFChatStyleManager.KEY_AVATAR_HANG.equals(key)) {
                return createAnimaTionDrawable(avatarHangPath, value, "avatar" + value, pattern);

            } else if (JFChatStyleManager.KEY_BUBBLE.equals(key)) {
                return createAnimaTionDrawable(bubblePath, value, "bubble" + value, pattern);

            } else if (JFChatStyleManager.KEY_INCOME_COLOR.equals(key)) {
                return createAnimaTionDrawable(bubblePath, value, "income" + value, pattern);

            } else if (JFChatStyleManager.KEY_OUT_COLOR.equals(key)) {
                return createAnimaTionDrawable(bubblePath, value, "out" + value, pattern);

            } else if ("emoji".equals(key)) {
                return createAnimaTionDrawable(emojiPath, value, "emoji" + value, pattern);

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


        return null;
    }


//    private synchronized static Drawable createAnimaTionDrawable(String path, Object value, String cacheKey) {
//        return createAnimaTionDrawable(path, value, cacheKey, DEFAULT_PATTERN);
//    }

    /**
     * 创建帧动画
     *
     * @param path     帧动画目录
     * @param value    帧动画类型
     * @param cacheKey 缓存帧动画的key
     * @return
     */
    private synchronized static Drawable createAnimaTionDrawable(String path, Object value, String cacheKey, int pattern) {
        if (animMap.containsKey(cacheKey)) {
            //tip 不能使用同一个drawable android drawable 重用并共用bitmap，生成一个新的对象drawable；
            // 不必重新从bitmap 或其他方式，重新解析生成drawable
            return getNewDrawable(animMap.get(cacheKey));
        }

        //定义的json文件
        File jsonFile = null;
        //当前目录所有文件
        String path1 = path + "/" + value;
        if (pattern == DEFAULT_MESSAGE_INCOMEING) {
            path1 = path1 + "/income";
        } else if (pattern == DEFAULT_MESSAGE_OUT) {
            path1 = path1 + "/out";
        }
        final List<File> files = FileUtils.listFilesInDir(path1);
        //drawable数组
        List<Drawable> drawables = new ArrayList<>();
        if (files == null) {
            return null;
        }
        if (files.size() == 0) {
            return null;
        }
        //for循环 创建drawable数组
        for (int i = 0; i < files.size(); i++) {
            if (files.get(i).getName().contains("json")) {
                jsonFile = files.get(i);
                continue;
            }
            if (!files.get(i).isFile()) {
                continue;
            }
            //处理.9图片
            if (files.get(i).getName().contains(".9")) {

                Bitmap bitmap = BitmapFactory.decodeFile(files.get(i).getAbsolutePath());
                // 如果.9.png没有经过aapt转换，那么chunk就是null
                byte[] chunk = bitmap.getNinePatchChunk();
                if (NinePatch.isNinePatchChunk(chunk)) {
                    NinePatchDrawable patchy = new NinePatchDrawable(bitmap, chunk, new Rect(), null);
                    drawables.add(patchy);
                }
            } else {
                Drawable drawable = Drawable.createFromPath(files.get(i).getAbsolutePath());
                drawables.add(drawable);
            }
        }
        if (drawables.size() == 0) {
            return null;
        }

        //如果json文件存在，解析json文件
        JSONObject jsonObject = null;
        try {
            if (jsonFile != null) {
                String json = readFile(jsonFile.getAbsolutePath());
                jsonObject = JSONObject.fromObject(json);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        //设置动画默认持续时间1500毫秒
        int duration = 1500 / drawables.size();
        //读取json中的动画持续时间
        if (jsonObject != null && jsonObject.containsKey("duration")) {
            String dString = jsonObject.getString("duration");
            if (!"".equals(dString)) {
                duration = (int) (Double.valueOf(dString) * 1000 / drawables.size());
            }
        }
        //播放次数（默认无限循环）
        int repeat = -1;
        if (jsonObject.containsKey("repeat")) {
            repeat = Integer.valueOf(jsonObject.getString("repeat"));
        }

        for (int a = 0; a < files.size(); a++) {
            if (files.get(a).getName().contains(".9")) {
                animMap.put(cacheKey, drawables.get(0));
                return drawables.get(0);
            }
        }

        //帧动画的 AnimationDrawable
        AnimationDrawable animationDrawable = new AnimationDrawable();
        if (repeat == 1) {
            animationDrawable.setOneShot(true);
        } else {
            animationDrawable.setOneShot(false);
        }
        for (int i = 0; i < drawables.size(); i++) {
            animationDrawable.addFrame(drawables.get(i), duration);
        }
        //放入缓存
        animMap.put(cacheKey, animationDrawable);

        return animationDrawable;
    }


    public static String readFile(String filePath) throws IOException {
        StringBuffer sb = new StringBuffer();
        readToBuffer(sb, filePath);
        return sb.toString();
    }

    public static void readToBuffer(StringBuffer buffer, String filePath) throws IOException {
        InputStream is = new FileInputStream(filePath);
        String line; // 用来保存每行读取的内容
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        line = reader.readLine(); // 读取第一行
        while (line != null) { // 如果 line 为空说明读完了
            buffer.append(line); // 将读到的内容添加到 buffer 中
            buffer.append("\n"); // 添加换行符
            line = reader.readLine(); // 读取下一行
        }
        reader.close();
        is.close();
    }

    /**
     * drawable 复制
     *
     * @param drawable
     * @return
     */
    public static Drawable getNewDrawable(Drawable drawable) {
        return drawable.getConstantState().newDrawable();
    }

    /**
     * 获取镜像图片（此方法对.9图无效）
     *
     * @param bitmap
     * @return
     */
    public static Bitmap mirrorImage(Bitmap bitmap) {
        //处理
        Bitmap modBm = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), bitmap.getConfig());
        //处理画布  重新绘制图形  形成镜像
        Canvas canvas = new Canvas(modBm);
        Paint paint = new Paint();
        //绘制矩阵  Matrix主要用于对平面进行平移(Translate)，缩放(Scale)，旋转(Rotate)以及斜切(Skew)操作。
        Matrix matrix = new Matrix();
        //镜子效果：
        matrix.setScale(-1, 1);//翻转
        matrix.postTranslate(bitmap.getWidth(), 0);

        canvas.drawBitmap(bitmap, matrix, paint);
        return modBm;
    }

    //清除帧动画缓存
    public static void clear() {
        animMap.clear();
    }
}
