package com.efounder.chat.item;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.efounder.chat.R;
import com.efounder.chat.item.manager.IMessageItem;
import com.efounder.frame.ViewSize;
import com.efounder.message.manager.JFMessageManager;
import com.efounder.message.struct.IMStruct002;
import com.efounder.pansoft.chat.animation.AnimationFactory;

import org.json.JSONObject;

/**
 * 动画 动图item
 *
 * @author yqs
 */
public class AnimationItem extends LinearLayout implements IMessageItem,
        View.OnClickListener {
    private static final String TAG = "AnimationItem";

    private Context mContext;
    private ImageView ivAnimView;
    private LinearLayout parentLayout;

    private IMStruct002 imStruct002;

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


    public AnimationItem(Context context) {
        super(context);
        mContext = context;
        initView(context);
    }

    private void initView(Context context) {
        LayoutInflater inflater = LayoutInflater.from(context);
        parentLayout = (LinearLayout) inflater.inflate(R.layout.chat_item_anim, this);
        ivAnimView = (ImageView) parentLayout.findViewById(R.id.ivAnimView);
        ivAnimView.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.ivAnimView) {
            // EventBus.getDefault().post(new AnimationEvent(imStruct002.getMessage()));
            AnimationFactory.startAnimFromIMStruct(mContext, imStruct002);
        }

    }

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

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

    @Override
    public void setIMStruct002(IMStruct002 message) {
        imStruct002 = message;
        // {"type":"animation","no":"00001","name":"gold","duration":"2.000000","repeat":"1"}
        try {
            JSONObject messageJsonObject = new JSONObject(message.getMessage());
            //判断动画是否已自动播放过
            if (!messageJsonObject.has("isFirstPlay")) {
                AnimationFactory.startAnimFromIMStruct(mContext, imStruct002);
                //更改消息体
                messageJsonObject.put("isFirstPlay", 0);
                message.setMessage(messageJsonObject.toString());
                //更新数据库中的消息
                JFMessageManager.dbManager.update(message);
            }

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


    }


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

    @Override
    public void setIsInUse(boolean isInUse) {
    }

    @Override
    public void prepareForReuse() {

    }


}
