package com.efounder.pansoft.chat.animation;

import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import androidx.core.content.ContextCompat;

import com.efounder.chat.R;
import com.efounder.chat.model.AnimationEvent;
import com.efounder.chat.model.AppConstant;
import com.efounder.chat.struct.MessageChildTypeConstant;
import com.efounder.message.struct.IMStruct002;
import com.utilcode.util.FileUtils;
import com.utilcode.util.ToastUtils;

import net.sf.json.JSONObject;

import org.greenrobot.eventbus.EventBus;

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

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * 管理帧动画读取
 */
public class AnimationFactory {

    public static void startAnimFromIMStruct(Context context, IMStruct002 imStruct002) {
        //fromUserId=181592; toUserId=2752; time=1523970266728;serverTime=1523970267234;
        // msgId=0; body={"type":"animation","name":"gold","no":"00001","duration":"2.000000","repeat":"1"}
        if (imStruct002.getMessageChildType() == MessageChildTypeConstant.subtype_anim) {
            startAnimFromMessageBody(context, imStruct002.getMessage());
        }
    }

    public static void startAnimFromMessageBody(Context context, String body) {
        //fromUserId=181592; toUserId=2752; time=1523970266728;serverTime=1523970267234;
        if (body == null || "".equals(body)) {
            return;
        }
        JSONObject jsonObject = null;
        try {
            jsonObject = JSONObject.fromObject(body);
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
        String name = jsonObject.optString("name", "");
        if ("gold".equals(name)) {
            startGoldAnimation(context, jsonObject);
        } else {
            startAnimationFromFile(context, jsonObject);
        }
    }

    private static void startAnimationFromFile(Context context, final JSONObject jsonObject) {
        String fileDir = AppConstant.APP_ROOT + "/res/unzip_res/Image/common/." + jsonObject.getString("type") + "/" + jsonObject.getString("name");
        final List<File> files = FileUtils.listFilesInDir(fileDir);
        if (files == null) {
                ToastUtils.showShort(R.string.wechatview_not_get_res);
            return;
        }
        if (files.size() == 0) {
            ToastUtils.showShort(R.string.wechatview_not_get_res);
            return;
        }
        Disposable disposable = Observable.create(new ObservableOnSubscribe<AnimationDrawable>() {

            @Override
            public void subscribe(ObservableEmitter<AnimationDrawable> emitter) throws Exception {
                List<Drawable> drawables = new ArrayList<>();
                for (int i = 0; i < files.size(); i++) {
                    Drawable drawable = Drawable.createFromPath(files.get(i).getAbsolutePath());
                    drawables.add(drawable);
                }

                int duration = (int) (Double.valueOf(jsonObject.getString("duration")) * 1000 / files.size());

                AnimationDrawable animationDrawable = new AnimationDrawable();
                animationDrawable.setOneShot(true);
                for (int i = 0; i < drawables.size(); i++) {
                    animationDrawable.addFrame(drawables.get(i), duration);
                }
                emitter.onNext(animationDrawable);
                emitter.onComplete();
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<AnimationDrawable>() {
                    @Override
                    public void accept(AnimationDrawable animationDrawable) throws Exception {
                        AnimationEvent event = new AnimationEvent();
                        event.setAnimationDrawable(animationDrawable);
                        double time = Double.valueOf(jsonObject.getString("duration")) * 1000;
                        event.setDurationTime((long) time);
                        EventBus.getDefault().post(event);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        ToastUtils.showShort(R.string.wechatview_not_get_res);
                    }
                });


    }


    //创建金币动画
    private static void startGoldAnimation(Context context, JSONObject jsonObject) {
        AnimationDrawable animationDrawable = (AnimationDrawable) ContextCompat.getDrawable(context, R.drawable.jf_frame_gold_top_to_bottom_animlist);
        animationDrawable.setOneShot(true);

        AnimationEvent event = new AnimationEvent();
        event.setAnimationDrawable(animationDrawable);
        double time = Double.valueOf(jsonObject.getString("duration")) * 1000;
        event.setDurationTime((long) time);
        EventBus.getDefault().post(event);
    }
}
