package com.baidu.ai.sample;

import android.animation.ValueAnimator;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baidu.ai.sample.cloudrender.CreateCloudStreamingRequest;
import com.baidu.ai.sample.cloudrender.DestroyCloudStreamingRequest;
import com.baidu.ai.sample.data.ChatBean;
import com.baidu.ai.sample.util.UIUtils;
import com.baidu.rtc.RTCVideoView;
import com.baidu.rtc.agent.Constants;

/**
 * 大模型多模态对话
 */
public class AiCloudRenderActivity extends AiChatBaseActivity {
    private static final String TAG = "AiCloudRenderActivity";
    private static final long CLOUD_RENDER_UID = 3;
    private EditText mInputText;
    private boolean mIsMicMute = false;
    /** 播放是否mute */
    private boolean mSpeakerIsMute = false;
    private FrameLayout mVideoLayout;
    private TextView mChatView;
    private String mCloudRenderAppKey;
    private String mCloudRenderAppSecret;
    private String mCloudRenderDesKey;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cloudrender_chat);
        mCloudRenderAppKey = this.getString(R.string.cloud_render_app_key);
        mCloudRenderAppSecret = this.getString(R.string.cloud_render_app_secret);
        mCloudRenderDesKey = this.getString(R.string.cloud_render_des_key);
        if (TextUtils.isEmpty(mCloudRenderAppKey) || TextUtils.isEmpty(mCloudRenderAppSecret)) {
            toastMsg("暂未对外开放云渲染功能！");
        }
        setupAgent();
    }

    @Override
    protected void initAllViews() {
        ((TextView) findViewById(R.id.tv_instance_name))
                .setText(String.format("instance_id：%s", mClientData.mInstanceId));

        findViewById(R.id.go_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AiCloudRenderActivity.this.finish();
            }
        });

        mInputText = (EditText) findViewById(R.id.input_text);

        mInputText.setText("用云渲染播放视频百度云宣传片");
        mInputText.setTextColor(getResources().getColor(R.color.colorPrimary));
        mInputText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
                if (actionId == EditorInfo.IME_ACTION_SEND || keyEvent.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
                    if (TextUtils.isEmpty(mInputText.getText().toString())) {
                        return false;
                    }

                    String text = mInputText.getText().toString();
                    aiController.sendText(text);
                    mChatView.setText("Me:" + text);
                    mInputText.setText("");
                    hideInput(mInputText);
                    return true;

                }
                return false;
            }
        });


        ((ImageView) findViewById(R.id.pause_call_imageview))
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        aiController.interrupt();
                    }
                });

        findViewById(R.id.mute_call_imageview).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mIsMicMute = !mIsMicMute;
                aiController.muteMic(mIsMicMute);
                ImageView iv = null;
                if (view instanceof ImageView) {
                    iv = (ImageView) view;
                }
                if (mIsMicMute) {
                    if (iv != null) {
                        iv.setImageDrawable(getDrawable(R.drawable.microphone_off));
                    }
                } else {
                    if (iv != null) {
                        iv.setImageDrawable(getDrawable(R.drawable.microphone_on));
                    }
                }
            }
        });

        findViewById(R.id.speaker_switch_imageview).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mSpeakerIsMute = !mSpeakerIsMute;
                aiController.mutePlayback(mSpeakerIsMute);
                ImageView iv = null;
                if (view instanceof ImageView) {
                    iv = (ImageView) view;
                    int id = mSpeakerIsMute ? R.drawable.btn_speaker_off : R.drawable.btn_speaker_on;
                    iv.setImageDrawable(getDrawable(id));
                }
            }
        });

        findViewById(R.id.upload_imageview).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("image/*");
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                mStartIntentResult.startActivityForResult(Intent.createChooser(intent, "选择图片"), REQUEST_IMAGE_CODE);
            }
        });

        LinearLayout toolsBottom = findViewById(R.id.listview_chat_tool);
        LinearLayout bottomActions = findViewById(R.id.bottom_actions);
        int maxHeight = UIUtils.dp2px(this, 152);
        int minHeight = UIUtils.dp2px(this, 72);
        findViewById(R.id.more_imageview).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int startHeight = toolsBottom.getHeight();
                boolean showBottom = startHeight >= maxHeight;
                int endHeight = startHeight >= maxHeight ? minHeight : maxHeight;
                bottomActions.setVisibility(showBottom ? View.GONE : View.VISIBLE);
                ValueAnimator animator = ValueAnimator.ofInt(startHeight, endHeight);
                animator.setDuration(300); // 动画持续时间
                animator.addUpdateListener(animation -> {
                    int animatedValue = (int) animation.getAnimatedValue();
                    toolsBottom.getLayoutParams().height = animatedValue;
                    toolsBottom.requestLayout(); // 重新布局
                });
                animator.start();
            }
        });
        findViewById(R.id.camera_imageview).setVisibility(View.GONE);

        mChatView = findViewById(R.id.tv_chat_view);
        mChatView.setVisibility(View.GONE);
        mVideoLayout = findViewById(R.id.video_container);
        mChatView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                mChatView.setVisibility(View.INVISIBLE);
                return false;
            }
        });


        aiController.setCloudRenderDisplay(mVideoLayout,
                new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT),
                RTCVideoView.ScalingType.SCALE_ASPECT_FIT);
    }

    @Override
    protected void onAIAgentGenerated(String instanceId) {
        super.onAIAgentGenerated(instanceId);
        CreateCloudStreamingRequest request = new CreateCloudStreamingRequest(mCloudRenderAppKey,
                mCloudRenderAppSecret, mCloudRenderDesKey);
        request.setAIInstanceId(instanceId);
        request.setCloudRenderUid(CLOUD_RENDER_UID + "");
        request.setRtcAppId(mClientData.mAppId);
        mHttpClient.asyncApiJsonBody(request.generateApiUrl(), request.generateEncryptBody(),
                new HttpClient.Callback() {
                    @Override
                    public void onResponse(int code, String res) {
                        Log.i(TAG, "onResponse:" + code + ",res:" + res);
                    }
                });
    }

    private ChatBean mLastAgentBean = null;
    private ChatBean mLastAsrBean = null;
    @Override
    protected void onUIAIAgentSubtitle(String text, boolean isFinal) {
        super.onUIAIAgentSubtitle(text, isFinal);
        Log.i(TAG, "onUIAIAgentSubtitle:" + text + ",is:" + isFinal);
        if (mChatView.getVisibility() != View.VISIBLE) {
            mChatView.setVisibility(View.VISIBLE);
        }
        if (!isFinal) {
            if (mLastAgentBean == null) {
                mLastAgentBean = new ChatBean(false, text);
            } else {
                mLastAgentBean.say += text;
            }
            mChatView.setText("小文:" + mLastAgentBean.say);
        } else {
            if (mLastAgentBean != null) {
                mLastAgentBean.say = text;
            } else {
                mLastAgentBean = new ChatBean(false, text);
            }
            mChatView.setText("小文:" + mLastAgentBean.say);
            mLastAgentBean = null;
        }
    }

    @Override
    protected void onUIAsrSubtitle(String text, boolean isFinal, Constants.ASRExtInfo info) {
        super.onUIAsrSubtitle(text, isFinal, info);
        Log.i(TAG, "onUIAIAgentSubtitle:" + text + ",is:" + isFinal);
        if (mChatView.getVisibility() != View.VISIBLE) {
            mChatView.setVisibility(View.VISIBLE);
        }
        if (!isFinal) {
            if (mLastAsrBean == null) {
                mLastAsrBean = new ChatBean(true, text);
            } else {
                mLastAsrBean.say = text;
            }
            mChatView.setText("我:" + mLastAsrBean.say);
        } else {
            if (mLastAsrBean != null) {
                mLastAsrBean.say = text;
                mLastAsrBean.time = ChatBean.getTime();
            } else {
                mLastAsrBean = new ChatBean(true, text);
            }

            mChatView.setText("我:" + mLastAsrBean.say);
            mLastAsrBean = null;
        }
    }

    @Override
    protected void onAIAgentStateChange(int state) {
        if (state == Constants.CallState.ON_CALL_BEGIN) {
            toastMsg("AI 云渲染已连接, 可尝试: 在云上播放视频、音频/打开图片、文档...");
        } else if (state == Constants.CallState.ON_CALL_END) {
            toastMsg("AI 云渲连接!");
        }
    }

    @Override
    protected void addFileUploadBean(int imageUsageScenario, String path) {
        super.addFileUploadBean(imageUsageScenario, path);
        mChatView.setText("上传图片: " + path);
    }

    @Override
    protected void onDestroy() {
        DestroyCloudStreamingRequest request = new DestroyCloudStreamingRequest(mCloudRenderAppKey,
                mCloudRenderAppSecret, mCloudRenderDesKey);
        request.setAIInstanceId(mClientData.mInstanceId);
        mHttpClient.asyncApiJsonBody(request.generateApiUrl(), request.generateEncryptBody(),
                new HttpClient.Callback() {
                    @Override
                    public void onResponse(int code, String res) {
                        Log.i(TAG, "onResponse:" + code + ",res:" + res);
                    }
                });
        super.onDestroy();
    }
}