/**
 * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.efounder.chat.adapter;

import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Looper;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.efounder.chat.R;
import com.efounder.chat.event.NotifyChatUIRefreshEvent;
import com.efounder.chat.http.OKHttpUtils;
import com.efounder.chat.model.VoicePlayingEvent;
import com.efounder.chat.struct.MessageChildTypeConstant;
import com.efounder.chat.utils.ImageUtil;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.utils.Constants;
import com.efounder.message.struct.IMStruct002;
import com.efounder.util.AppContext;

import net.sf.json.JSONObject;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

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

public class ChatVoicePlayClickListener implements View.OnClickListener {

    private IMStruct002 imStruct002;
    private ImageView voiceIconView;
    private ImageView iv_read_status;
    private AnimationDrawable voiceAnimation = null;
    private MediaPlayer mediaPlayer = null;


    private Context activity;
    public static String currentMsgId;
    //当前播放的文件路径
    private static String currentFilePath;
    //chatactivity结束的时候 记得回收
    public static ChatVoicePlayClickListener currentPlayListener = null;
    public static boolean isPlaying = false;
    //存储语音播放的回调 类似于一个数组，key是消息id
    private static Map<String, PlayVocieCallBack> vocieCallBacks = new HashMap<>();

    /**
     * 语音播放（普通语音消息）
     *
     * @param imStruct002 消息体
     * @param v           动画的view
     * @param unReadView  未读的view
     * @param activity
     */
    public ChatVoicePlayClickListener(IMStruct002 imStruct002, ImageView v,
                                      ImageView unReadView, Context activity) {
        this.imStruct002 = imStruct002;
        //voiceBody = imStruct002.getBody();
        iv_read_status = unReadView;
        voiceIconView = v;
        this.activity = activity;
        // this.adapter = adapter;
        imStruct002.putExtra("isPlaying", false);
        isPlaying = (boolean) imStruct002.getExtra("isPlaying");
    }

    /**
     * 语音播放(语音识别消息使用此方法) yqs
     *
     * @param imStruct002
     * @param activity
     */
    public ChatVoicePlayClickListener(IMStruct002 imStruct002, Context activity, PlayVocieCallBack playVocieCallBack) {
        this.imStruct002 = imStruct002;
        //voiceBody = imStruct002.getBody();
        this.activity = activity;
        if (imStruct002.getExtra("isPlaying") == null) {
            imStruct002.putExtra("isPlaying", false);
        }
        //isPlaying = (boolean) imStruct002.getExtra("isPlaying");
        vocieCallBacks.put(imStruct002.getMessageID(), playVocieCallBack);

    }




    @Override
    public void onClick(View v) {
        if (currentMsgId != null) {
            if (currentMsgId.equals(imStruct002.getMessageID())) {
                if ((boolean) imStruct002.getExtra("isPlaying")) {
                    if (currentPlayListener != null) {
                        currentPlayListener.stopPlayVoice();
                    }
                    EventBus.getDefault().post(new VoicePlayingEvent(false));
                    currentMsgId = null;
                    return;
                }
            } else if (!currentMsgId.equals(imStruct002.getMessageID())) {
                if (currentPlayListener != null) {
                    currentPlayListener.stopPlayVoice();
                }
                EventBus.getDefault().post(new VoicePlayingEvent(false));
            }

        }
        JSONObject jsonObject = JSONObject.fromObject(imStruct002.getMessage());
        String voicePath = getVoiceFileUrlOrPath(imStruct002);

        if (voicePath.startsWith("http")) {
            String fileNote = voicePath.substring(0, voicePath.lastIndexOf("/"));
            if (jsonObject.optString("device", "").equals("iOS")) {
                try {
                    String fileName = ImageUtil.amrpath + fileNote.substring(fileNote.lastIndexOf("/") + 1);
                    File file = new File(fileName + ".aac");
                    if (!file.exists()) {
                        OKHttpUtils.downLoadFiles(activity, MessageChildTypeConstant.subtype_voice,
                                voicePath, fileName + ".aac", null, new OKHttpUtils.DownloadListener() {
                                    @Override
                                    public void onSuccess(final String path) {
                                        currentFilePath = path;
                                   new android.os.Handler(Looper.getMainLooper()).post(new Runnable() {
                                       @Override
                                       public void run() {
                                           playVoice(path);
                                       }
                                   });

                                    }

                                    @Override
                                    public void onFailure() {

                                    }
                                });
                    } else {
                        currentFilePath = fileName + ".aac";

                        playVoice(fileName + ".aac");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                try {

                    String fileName = ImageUtil.amrpath + fileNote.substring(fileNote.lastIndexOf("/") + 1);
                    File file = new File(fileName + ".amr");
                    if (!file.exists()) {
                        //String desLoadURL = OKHttpUtils.createTempDir(UUID.randomUUID()+"", ".amr");
                        //String desLoadURL = OKHttpUtils.createTempDir(fileName, ".amr");
                        OKHttpUtils.downLoadFiles(activity, MessageChildTypeConstant.subtype_voice,
                                voicePath, fileName + ".amr", null, new OKHttpUtils.DownloadListener() {
                                    @Override
                                    public void onSuccess(final String path) {
                                        currentFilePath = path;

                                        new android.os.Handler(Looper.getMainLooper()).post(new Runnable() {
                                            @Override
                                            public void run() {
                                                playVoice(path);
                                            }
                                        });
                                    }

                                    @Override
                                    public void onFailure() {

                                    }
                                });
                    } else {
                        currentFilePath = fileName + ".amr";
                        playVoice(fileName + ".amr");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else {
            //播放本地语音
            currentFilePath = voicePath;
            playVoice(voicePath);
        }

    }

    //停止播放
    public void stopPlayVoice() {
        stopPlayVocieCallBackNotify();

        if (null != voiceAnimation) {
            voiceAnimation.stop();
        }
        if (voiceIconView != null) {
            if (Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID)) !=
                    imStruct002.getFromUserId()) {//代表 对方发来的语音
                voiceIconView.setImageResource(R.drawable.chatfrom_voice_playing);
            } else {
                voiceIconView.setImageResource(R.drawable.chatto_voice_playing);
            }
        }

        // stop play voice
        try {
            if (mediaPlayer != null) {
                mediaPlayer.stop();
                mediaPlayer.release();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        isPlaying = false;
        imStruct002.putExtra("isPlaying", false);
        //currentFilePath = null;
    }

    //结束播放通知
    private void stopPlayVocieCallBackNotify() {
        PlayVocieCallBack callBack = vocieCallBacks.get(currentMsgId);
        if (callBack != null) {
            callBack.stopPlay(currentMsgId);
        }
    }

    //开始播放通知
    private void startPlayVocieCallBackNotify() {
        PlayVocieCallBack callBack = vocieCallBacks.get(currentMsgId);
        if (callBack != null) {
            callBack.startPlay(currentMsgId);
        }
    }

    public void playVoice(String filePath) {
        String type = EnvironmentVariable.getProperty("voicePlayType", "0");
        playVoice(filePath, Integer.valueOf(type));
    }
    //type 播放方式 0 听筒 1 外放
    public void playVoice(String filePath, int type) {
        currentMsgId = imStruct002.getMessageID();
        if (!(new File(filePath).exists())) {
            Toast.makeText(activity, R.string.wrchatview_damage_file, Toast.LENGTH_SHORT).show();
            currentMsgId = null;
            return;
        }

        AudioManager audioManager = (AudioManager) activity
                .getSystemService(Context.AUDIO_SERVICE);

        mediaPlayer = new MediaPlayer();

        if (1 == type) {
            audioManager.setMode(AudioManager.MODE_NORMAL);
            audioManager.setSpeakerphoneOn(true);
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_RING);
        } else {
            audioManager.setSpeakerphoneOn(false);// 关闭扬声器
            // 把声音设定成Earpiece（听筒）出来，设定为正在通话中
            audioManager.setMode(AudioManager.MODE_IN_CALL);
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
        }
        try {
            mediaPlayer.setDataSource(filePath);
            mediaPlayer.prepare();
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

                @Override
                public void onCompletion(MediaPlayer mp) {
                    // TODO Auto-generated method stub
                    if (mediaPlayer == null) {
                        return;
                    }
                    mediaPlayer.release();
                    mediaPlayer = null;
                    stopPlayVoice(); // stop animation
                    EventBus.getDefault().post(new VoicePlayingEvent(false));

                    //发送通知刷新界面
                    EventBus.getDefault().post(new NotifyChatUIRefreshEvent());


                }

            });
            //设置正在播放
            imStruct002.putExtra("isPlaying", true);
            isPlaying = true;
            currentPlayListener = this;
            mediaPlayer.start();
            showAnimation();
            EventBus.getDefault().post(new VoicePlayingEvent(true));
            startPlayVocieCallBackNotify();

        } catch (Exception e) {
            e.printStackTrace();
            currentMsgId = null;
            imStruct002.putExtra("isPlaying", false);
            isPlaying = false;
        }
    }

    //语音消息显示动画
    private void showAnimation() {
        if (voiceIconView == null) {
            return;
        }
        if (Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID)) !=
                imStruct002.getFromUserId()) {
            voiceIconView.setImageResource(R.drawable.voice_from_icon);
        } else {
            voiceIconView.setImageResource(R.drawable.voice_to_icon);
        }
        voiceAnimation = (AnimationDrawable) voiceIconView.getDrawable();
        voiceAnimation.start();
    }


    //获取语音文件路径
    public static String getVoiceFileUrlOrPath(IMStruct002 imStruct002) {
        JSONObject jsonObject = JSONObject.fromObject(imStruct002.getMessage());
        String voicePath;
        if (!imStruct002.getMessage().contains("url")) {
            voicePath = imStruct002.getMessage();
        } else if (imStruct002.getFromUserId() == Integer.valueOf(EnvironmentVariable.getProperty(Constants.CHAT_USER_ID))) {
            voicePath = jsonObject.optString("path", "");
            if (!new File(voicePath).exists()) {
                //本地问价不存在，取服务器
                voicePath = jsonObject.optString("url", "");
            }
        } else {
            voicePath = jsonObject.optString("url", "");
        }
        return voicePath;
    }

    //下载语音文件
    public static void downLoadVoiceFile(final IMStruct002 imStruct002, final DownLoadVoiceFileCallBack loadVoiceFileCallBack) {
        String voicePath = getVoiceFileUrlOrPath(imStruct002);
        JSONObject jsonObject = JSONObject.fromObject(imStruct002.getMessage());
        if (voicePath.startsWith("http")) {
            String fileNote = voicePath.substring(0, voicePath.lastIndexOf("/"));
            if (jsonObject.optString("device", "").equals("iOS")) {
                try {
                    final String fileName = ImageUtil.amrpath + fileNote.substring(fileNote.lastIndexOf("/") + 1);
                    File file = new File(fileName + ".aac");
                    if (!file.exists()) {
                        //String desLoadURL = OKHttpUtils.createTempDir(UUID.randomUUID()+"", ".amr");
                        //String desLoadURL = OKHttpUtils.createTempDir(fileName, ".amr");
                        OKHttpUtils.downLoadFiles(AppContext.getInstance(), MessageChildTypeConstant.subtype_voice,
                                voicePath, fileName + ".aac", null, new OKHttpUtils.DownloadListener() {
                                    @Override
                                    public void onSuccess(final String path) {
                                        new android.os.Handler(Looper.getMainLooper()).post(new Runnable() {
                                            @Override
                                            public void run() {
                                                loadVoiceFileCallBack.onSuccess(path, imStruct002.getMessageID());
                                            }
                                        });

                                    }

                                    @Override
                                    public void onFailure() {

                                    }
                                });
                    } else {
                        loadVoiceFileCallBack.onSuccess(fileName + ".aac", imStruct002.getMessageID());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                try {
                    String fileName = ImageUtil.amrpath + fileNote.substring(fileNote.lastIndexOf("/") + 1);
                    File file = new File(fileName + ".amr");
                    if (!file.exists()) {
                        OKHttpUtils.downLoadFiles(AppContext.getInstance(), MessageChildTypeConstant.subtype_voice,
                                voicePath, fileName + ".amr", null, new OKHttpUtils.DownloadListener() {
                                    @Override
                                    public void onSuccess(final String path) {
                                        new android.os.Handler(Looper.getMainLooper()).post(new Runnable() {
                                            @Override
                                            public void run() {
                                                loadVoiceFileCallBack.onSuccess(path, imStruct002.getMessageID());
                                            }
                                        });
                                    }

                                    @Override
                                    public void onFailure() {
                                        loadVoiceFileCallBack.onFail();
                                    }
                                });
                    } else {
                        loadVoiceFileCallBack.onSuccess(fileName + ".amr", imStruct002.getMessageID());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else {
            loadVoiceFileCallBack.onSuccess(voicePath, imStruct002.getMessageID());
        }

    }

    /**
     * 设置播放方式
     *
     * @param type 0 听筒播放 1 免提播放
     */
    public static void setPlayType(int type) {
        if (currentPlayListener != null) {
            if (isPlaying) {
                currentPlayListener.stopPlayVoice();
            }
            if (currentFilePath != null) {
                currentPlayListener.playVoice(currentFilePath, type);
            }
        }
    }

    public static void clearCallBacks() {
        vocieCallBacks.clear();
    }

    public interface PlayVocieCallBack {
        //开始播放
        void startPlay(String msgId);

        //停止播放
        void stopPlay(String msgId);
    }

    public interface DownLoadVoiceFileCallBack {

        void onSuccess(String filePath, String messageID);

        void onFail();
    }
}