package com.example.leudaemialikeme.Activity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.leudaemialikeme.Adapter.ChatAdapter;
import com.example.leudaemialikeme.Dao.FriendDao;
import com.example.leudaemialikeme.Dao.MessageDao;
import com.example.leudaemialikeme.Model.Friend;
import com.example.leudaemialikeme.Model.Message;
import com.example.leudaemialikeme.Model.MessageItemView;
import com.example.leudaemialikeme.R;
import com.example.leudaemialikeme.Utils.TimeUtil;
import com.google.gson.Gson;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class ChatActivity extends BaseActivity {
    private MessageDao messageDao = new MessageDao();
    private FriendDao friendDao = new FriendDao();
    private ImageButton bt_chat_to_chat_list;
    private RecyclerView msg_recycler_view;
    private TextView text_chat_name;
    private EditText edit_content;
    private Button bt_send_msg;
    public int friendNetId;
    private Friend currentFriend;
    private ArrayList<Message> messageList = new ArrayList<Message>();
    private MessageItemView msgItemView;
    private ChatAdapter chatAdapter;
    private Gson gson = new Gson();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
        bt_chat_to_chat_list = findViewById(R.id.bt_chat_to_chat_list);
        msg_recycler_view = findViewById(R.id.msg_recycler_view);
        text_chat_name = findViewById(R.id.text_chat_name);
        edit_content = findViewById(R.id.edit_content);
        bt_send_msg = findViewById(R.id.bt_send_msg);

        initData();
        text_chat_name.setText(currentFriend.getUsername());

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        msg_recycler_view.setLayoutManager(layoutManager);
        chatAdapter = new ChatAdapter(msgItemView);
        msg_recycler_view.setAdapter(chatAdapter);
        msg_recycler_view.scrollToPosition(messageList.size() - 1);
        edit_content.setImeOptions(EditorInfo.IME_ACTION_SEND);
        edit_content.setInputType(EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE);
        edit_content.setMaxLines(2);
        edit_content.setSingleLine(false);
        edit_content.setOnEditorActionListener(new TextView.OnEditorActionListener() {
           @Override
           public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
               if (actionId == EditorInfo.IME_ACTION_SEND
                       || actionId == EditorInfo.IME_ACTION_DONE
                       || (event != null && KeyEvent.KEYCODE_ENTER == event.getKeyCode() && KeyEvent.ACTION_DOWN == event.getAction())) {
                   String content=edit_content.getText().toString();
                   if (!content.equals("")){
                       Message message =new Message(owner.getNetId(),currentFriend.getNetId(),content);
                       Map<String, String> jsonMap = new HashMap<String, String>();
                       jsonMap.put("senderNetId", String.valueOf(owner.getNetId()));
                       jsonMap.put("receiverNetId", String.valueOf(currentFriend.getNetId()));
                       jsonMap.put("messageType","1");
                       jsonMap.put("content", content);
                       jsonMap.put("createTime", TimeUtil.timeToString(new Timestamp(message.getCreateTime())));
                       addMsg(message,1);
                       edit_content.setText("");
                       wsClient.send(gson.toJson(jsonMap));
                   }
               }
               return false;
           }
       });
        bt_send_msg.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                String content=edit_content.getText().toString();
                if (!content.equals("")){
                    Message message =new Message(owner.getNetId(),currentFriend.getNetId(),content);
                    Map<String, String> jsonMap = new HashMap<String, String>();
                    jsonMap.put("senderNetId", String.valueOf(owner.getNetId()));
                    jsonMap.put("receiverNetId", String.valueOf(currentFriend.getNetId()));
                    jsonMap.put("messageType","1");
                    jsonMap.put("content", content);
                    jsonMap.put("createTime", TimeUtil.timeToString(new Timestamp(message.getCreateTime())));
                    addMsg(message,1);
                    edit_content.setText("");
                    wsClient.send(gson.toJson(jsonMap));
                }
            }
        });
        bt_chat_to_chat_list.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void initData() {
        //从intent中取出currentNetId并查出对象
        Intent intent = getIntent();
        friendNetId = intent.getIntExtra("friendNetId", -1);
        Log.d("ChatActivity","当前聊天对象ID："+friendNetId);
        currentFriend = friendDao.findByNetId(friendNetId, owner.getNetId());
        Log.d("ChatActivity","当前聊天对象："+currentFriend);
        //从数据库中查找聊天记录-默认最近20条记录
        messageList = messageDao.findNearlyMessage(friendNetId, owner.getNetId());
        //组装成MessageItemViw
        msgItemView = new MessageItemView(currentFriend, owner, messageList);
    }

    //消息添加方法
    public void addMsg(Message message, int isRead) {
        Log.d("刷新","添加一条新消息");
        msgItemView.messages.add(message);
        chatAdapter.notifyItemInserted(messageList.size() - 1);
        msg_recycler_view.scrollToPosition(messageList.size() - 1);
        message.setFlag(isRead);
        message.save();
    }
}