package com.efounder.chat.item;

import android.app.Activity;
import android.content.Context;
import androidx.constraintlayout.widget.ConstraintLayout;
import android.util.DisplayMetrics;
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 android.widget.TextView;

import com.efounder.chat.R;
import com.efounder.chat.adapter.ChatVoicePlayClickListener;
import com.efounder.chat.item.manager.IMessageItem;
import com.efounder.chat.utils.VoiceRecognitionSoundFileCacheUtil;
import com.efounder.chat.view.voicedictate.SoundFile;
import com.efounder.chat.view.voicedictate.WaveformView;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.ViewSize;
import com.efounder.message.struct.IMStruct002;
import com.efounder.ui.util.DisplayUtil;
import com.utilcode.util.SizeUtils;

import java.io.File;

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

/**
 * 语音识别 item
 *
 * @author YQS
 */
public class VoiceRecognitionItem extends ConstraintLayout implements IMessageItem {

    private static final String TAG = "VoiceRecognitionItem";


    private Context mContext;
    private LayoutInflater mInflater;
    private IMStruct002 iMStruct002;


    private View rootView;
    private LinearLayout rllayout;
    private TextView tvContent;
    // private View viewLine;
    private ImageView ivPlay;
    private WaveformView viewVoiceLine;
    private ImageView ivBottomPlay;
    private RelativeLayout rlBottomLayout;


    //是否是发送的消息
    private boolean isSend;
    //是否加载过,防止重复加载波形图
    //private boolean isLoaded;
    File mFile;
    Thread mLoadSoundFileThread;
    SoundFile mSoundFile;
    boolean mLoadingKeepGoing;

    public VoiceRecognitionItem(Context context) {
        super(context);
        this.mContext = context;
        mInflater = LayoutInflater.from(context);
        initView();
    }


    private void initView() {
        rootView = (ConstraintLayout) mInflater.inflate(R.layout.chat_item_voice_recognition, this);

        rllayout = (LinearLayout) findViewById(R.id.rllayout);
        tvContent = (TextView) findViewById(R.id.tv_content);
        //viewLine = (View) findViewById(R.id.view_line);
        ivPlay = (ImageView) findViewById(R.id.iv_play);
        viewVoiceLine = (WaveformView) findViewById(R.id.view_voice_line);
        ivBottomPlay = (ImageView) findViewById(R.id.iv_bottom_play);
        rlBottomLayout = (RelativeLayout) findViewById(R.id.rl_bottom_layout);
        viewVoiceLine.setShowCenterLine(true);
        LayoutParams lp = new LayoutParams(DisplayUtil.getMobileWidth(mContext) * 2 / 3 + 20,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        this.setLayoutParams(lp);
    }


    @Override
    public View messageView() {

        return this;
    }

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


    @Override
    public void setIMStruct002(IMStruct002 message) {
        this.iMStruct002 = message;
        onDataChanged();
    }

    private void onDataChanged() {
        if (iMStruct002.getFromUserId() == Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID))) {
            //自己发送的消息
            isSend = true;
            ivBottomPlay.setImageDrawable(mContext.getResources().getDrawable(R.drawable.qqstyle_chat_icon_send_voice_start));
            rllayout.setBackground(mContext.getResources().getDrawable(R.drawable.wechatview_shape_message_item_voice_recognition_send));
            ivPlay.setImageDrawable(mContext.getResources().getDrawable(R.drawable.qqstyle_chat_icon_send_voice_start));
            rlBottomLayout.setBackground(mContext.getResources().getDrawable(R.drawable.wechatview_shape_message_item_voice_recognition_shape_send));

        } else {
            isSend = false;
            ivBottomPlay.setImageDrawable(mContext.getResources().getDrawable(R.drawable.qqstyle_chat_icon_receive_voice_start));
            rllayout.setBackground(mContext.getResources().getDrawable(R.drawable.wechatview_shape_message_item_voice_recognition_received));
            ivPlay.setImageDrawable(mContext.getResources().getDrawable(R.drawable.qqstyle_chat_icon_receive_voice_start));
            rlBottomLayout.setBackground(mContext.getResources().getDrawable(R.drawable.wechatview_shape_message_item_voice_recognition_bottom_shape_received));

        }
        //判断播放状态
        if (iMStruct002.getExtra("isPlaying") == null) {
            iMStruct002.putExtra("isPlaying", false);
            setIvPlayImage(false);
        } else {
            setIvPlayImage((Boolean) iMStruct002.getExtra("isPlaying"));
        }
        //判断播放控制区是否显示
        if (iMStruct002.getExtra("playControlShow") != null && "1".equals(iMStruct002.getExtra("playControlShow"))) {
            showPlayControlView();
        } else {
            hidePlayControlView();
        }

        //todo 下载音频文件  主要是为了解析音频振幅
        ChatVoicePlayClickListener.downLoadVoiceFile(iMStruct002, new ChatVoicePlayClickListener.DownLoadVoiceFileCallBack() {
            @Override
            public void onSuccess(String filePath, String messageID) {
                loadFromFile(filePath, messageID);
            }

            @Override
            public void onFail() {

            }
        });
        try {
            net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(iMStruct002.getMessage());
            String text = jsonObject.optString("text");
            tvContent.setText(text);
        } catch (Exception e) {
            e.printStackTrace();
        }


        initListener();
    }

    //设置是否正在播放的图标
    public void setIvPlayImage(Boolean isPlaying) {
        if (isPlaying) {
            if (isSend) {
                ivPlay.setImageDrawable(mContext.getResources().getDrawable(R.drawable.qqstyle_chat_icon_send_voice_stop));
            } else {
                ivPlay.setImageDrawable(mContext.getResources().getDrawable(R.drawable.qqstyle_chat_icon_receive_voice_stop));
            }
        } else {
            if (isSend) {
                ivPlay.setImageDrawable(mContext.getResources().getDrawable(R.drawable.qqstyle_chat_icon_send_voice_start));
            } else {
                ivPlay.setImageDrawable(mContext.getResources().getDrawable(R.drawable.qqstyle_chat_icon_receive_voice_start));
            }
        }

    }

    private void initListener() {
        //设置播放监听 为了改变播放按钮
        ChatVoicePlayClickListener chatVoicePlayClickListener = new ChatVoicePlayClickListener(iMStruct002, mContext, new ChatVoicePlayClickListener.PlayVocieCallBack() {
            @Override
            public void startPlay(String msgID) {
                if (!iMStruct002.getMessageID().equals(msgID)) {
                    return;
                }
                if (isSend) {
                    ivPlay.setImageDrawable(mContext.getResources().getDrawable(R.drawable.qqstyle_chat_icon_send_voice_stop));
                } else {
                    ivPlay.setImageDrawable(mContext.getResources().getDrawable(R.drawable.qqstyle_chat_icon_receive_voice_stop));
                }
            }

            @Override
            public void stopPlay(String msgID) {
                if (!iMStruct002.getMessageID().equals(msgID)) {
                    return;
                }
//                ivPlay.setImageDrawable(mContext.getResources().getDrawable(R.drawable.qqstyle_voice_record_play_selector));
                if (isSend) {
                    ivPlay.setImageDrawable(mContext.getResources().getDrawable(R.drawable.qqstyle_chat_icon_send_voice_start));
                } else {
                    ivPlay.setImageDrawable(mContext.getResources().getDrawable(R.drawable.qqstyle_chat_icon_receive_voice_start));
                }
            }
        });

        ivPlay.setOnClickListener(chatVoicePlayClickListener);
        this.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
//                if(!isLoaded){
//                    isLoaded = true;
//                }else {
                showPlayControlView();
                ivPlay.performClick();
                //消息标记为隐藏view 已经显示
                iMStruct002.putExtra("playControlShow", "1");
                //}

            }
        });
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        // iMStruct002.putExtra("playControlShow", "0");
        try {
            if (mLoadSoundFileThread!=null && mLoadSoundFileThread.isAlive()){
                mLoadSoundFileThread.interrupt();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void showPlayControlView() {
//        viewLine.setVisibility(View.VISIBLE);
//        ivPlay.setVisibility(View.VISIBLE);
//        viewVoiceLine.setVisibility(View.VISIBLE);
        rlBottomLayout.setVisibility(View.VISIBLE);
        ivBottomPlay.setVisibility(View.GONE);
        rllayout.setPadding(rllayout.getPaddingLeft(), rllayout.getPaddingTop(), rllayout.getPaddingRight(), 0);
    }

    private void hidePlayControlView() {
//        viewLine.setVisibility(View.GONE);
//        ivPlay.setVisibility(View.GONE);
//        viewVoiceLine.setVisibility(View.GONE);
        ivBottomPlay.setVisibility(View.VISIBLE);
        rlBottomLayout.setVisibility(View.GONE);
        rllayout.setPadding(rllayout.getPaddingLeft(), rllayout.getPaddingTop(), rllayout.getPaddingRight(), SizeUtils.dp2px(6));


    }

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

    @Override
    public void setIsInUse(boolean isInUse) {
    }

    @Override
    public void prepareForReuse() {
    }


    /**
     * 载入音频文件显示波形
     *
     * @param path
     */
    private void loadFromFile(String path, final String messageId) {
        if (iMStruct002 == null) {
            return;

        }
        if (!iMStruct002.getMessageID().equals(messageId)) {
            return;
        }
        SoundFile mySoundFile = VoiceRecognitionSoundFileCacheUtil.getFromMessageList(iMStruct002.getMessageID());
        if (mySoundFile != null) {
            //缓存不为空s
            mSoundFile = mySoundFile;
            finishOpeningSoundFile(messageId);
            return;
        }

//        try {
//            Thread.sleep(300);//让文件写入完成后再载入波形 适当的休眠下
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        mFile = new File(path);
        mLoadingKeepGoing = true;
        // Load the sound file in a background thread
        mLoadSoundFileThread = new Thread() {
            public void run() {
                try {
                    mSoundFile = SoundFile.create(mFile.getAbsolutePath(), null);
                    if (mSoundFile == null) {
                        return;
                    }
                    VoiceRecognitionSoundFileCacheUtil.addMessageList(iMStruct002.getMessageID(), mSoundFile);
//                    mPlayer = new SamplePlayer(mSoundFile);
                } catch (final Exception e) {
                    e.printStackTrace();
                    return;
                }
                if (mLoadingKeepGoing) {
                    Runnable runnable = new Runnable() {
                        public void run() {
                            finishOpeningSoundFile(messageId);

                        }
                    };
                    if(!Thread.currentThread().isInterrupted()){
                        ((Activity) mContext).runOnUiThread(runnable);
                    }

                }
            }
        };
        mLoadSoundFileThread.start();
    }


    float mDensity;

    /**
     * 音频文件载入波形完成
     *
     * @param messageId
     */

    private void finishOpeningSoundFile(String messageId) {
        if (iMStruct002 == null) {
            return;
        }
        if (!iMStruct002.getMessageID().equals(messageId)) {
            return;
        }

        try {
            viewVoiceLine.setSoundFile(mSoundFile);
            DisplayMetrics metrics = new DisplayMetrics();
            ((Activity) mContext).getWindowManager().getDefaultDisplay().getMetrics(metrics);
            mDensity = metrics.density;
            viewVoiceLine.recomputeHeights(mDensity);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
