package com.example.leudaemialikeme.service;

import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.RequiresApi;

import com.example.leudaemialikeme.Activity.ChatActivity;
import com.example.leudaemialikeme.Activity.MainActivity;
import com.example.leudaemialikeme.Controller.ActivityController;
import com.example.leudaemialikeme.Fragment.MessageChannelFragment;
import com.example.leudaemialikeme.Fragment.MessageFragment;
import com.example.leudaemialikeme.Model.Message;
import com.example.leudaemialikeme.R;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.sql.Timestamp;
import java.util.Map;
import java.util.Objects;

public class WebSocketClient extends org.java_websocket.client.WebSocketClient {

    private Activity currentActivity;
    private ChatActivity chatActivity;///////////////////
//    private PrivateMsgFragment privateMsgFragment;////////////////////////
//    private FriendDao friendDao;
    private Gson gson = new Gson();

    public static final int MSG_TEXT=1;
    public static final int MSG_IMAGE=2;
    public static final int MSG_SYSTEM=3;
    private MainActivity mainActivity;


    public WebSocketClient(URI serverURI){
        super(serverURI,new Draft_6455());
    }

    @Override
    public void onOpen(ServerHandshake handshakedata) {
        Log.d("WS","链接开启");
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void onMessage(String message){
        try {
//            friendDao=new FriendDao();
            Log.d("WS",message+" onMessage()回调");
            //提取消息
            Map<String, String> jsonMap = gson.fromJson(message, new TypeToken<Map<String, String>>() {}.getType());
            String content = jsonMap.get("content");
            int messageType = Integer.parseInt(Objects.requireNonNull(jsonMap.get("messageType")));
            int receiverId = Integer.parseInt(Objects.requireNonNull(jsonMap.get("receiverNetId")));
            int senderId = Integer.parseInt(Objects.requireNonNull(jsonMap.get("senderNetId")));
            long createTime = Timestamp.valueOf(jsonMap.get("createTime")).getTime();
            Message newMessage=new Message(senderId,receiverId,messageType, content, createTime);
            Log.d("刷新","获取到对面发送的消息");
            //获取当前活动对象
            currentActivity= ActivityController.getCurrentActivity();
            //根据消息类型进行判断
            String currentActivityName=currentActivity.getLocalClassName();
            Log.d("刷新","当前活动名："+currentActivityName);
            if (messageType==MSG_SYSTEM){
                if (content.equals("offline")){
                    offline();
                }
            }else {
                //如果当前活动为聊天活动则进行数据展示
                if (currentActivityName.equals("Activity.ChatActivity")){
                    Log.d("刷新","当前在聊天界面活动页");
                    updateChatUi(newMessage);
//                    如果当前活动为聊天列表界面，需要对指定的元素进行局部更新，如果没有该用户在聊天列表中，需要添加该好友项
                }else if (currentActivity.findViewById(R.id.chat_list_layout)!=null){
                    newMessage.save();
                    updateChatListUi();
                }else{
                    newMessage.save();
                    notification();
                    updateChatListUi();
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void offline(){
        currentActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Intent intent=new Intent("FORCE_OFFLINE");
                intent.putExtra("warringMsg","您的账号异地登录，您将被强制下线");
                currentActivity.sendBroadcast(intent);
            }
        });
    }

    public void updateChatUi(final Message newMessage){
        currentActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                chatActivity = (ChatActivity) currentActivity;
                //如果当前正在聊天的人为消息的发送者，则进行展示,并存为已读消息
                if (chatActivity.friendNetId == newMessage.getSenderNetId()){
                    Log.d("刷新","当前聊天的人与消息发送者为同一人");
                    chatActivity.addMsg(newMessage,1);
                }
                //如果当前正在聊天的人不是消息发送者，则更新一个未读标记
                else {
//                    chatActivity.hasNewMsgView.setVisibility(View.VISIBLE);
                    newMessage.setFlag(0);
                    newMessage.save();
                }
            }
        });
    }

    public void updateChatListUi(){
        currentActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mainActivity = (MainActivity) currentActivity;
//                FragmentManager fm = mainActivity.getSupportFragmentManager();
//                Log.d("刷新","当前碎片管理："+fm.toString());
//                MessageChannelFragment mcf = (MessageChannelFragment) fm.findFragmentById(R.id.fragment_message_channel);
//                Log.d("刷新","当前所在碎片："+mcf);
//                MessageChannelFragment msgcf = (MessageChannelFragment) mainActivity.getSupportFragmentManager().findFragmentById(R.id.fragment_message_channel);
//                MessageChannelFragment mcf = new MessageChannelFragment();
                MessageFragment mf = (MessageFragment) mainActivity.getFragment(2);
                MessageChannelFragment mcf = mf.getAdapter().getMcf(0);
                Log.d("当前碎片的名字滑动页：", mcf.getMessageCategoryTitle());
                mcf.updateUi();
                Log.d("刷新","聊天列表刷新完成");
            }
        });
    }
    public void notification(){
        currentActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(currentActivity,"您有新的消息，请查收",Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onClose(int code, String reason, boolean remote) {
        Log.d("WS","链接关闭");
    }

    @Override
    public void onError(Exception ex) {
        ex.printStackTrace();
    }

//    //好友数据同步
//    private void getNewFriends(final int friendNetId,final int ownerNetId){
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                try {
//                    String url = BaseActivity.SERVER_URL + "/user/getNewFriendById/"+ownerNetId+"/"+friendNetId;
//                    String jsonStr= OkHttpUtil.synGet(url);
//                    getNewFriendsResponse(jsonStr);
//                }catch (Exception e){
//                    e.printStackTrace();
//                }
//            }
//        }).start();
//    }
//    private void getNewFriendsResponse(final String jsonStr){
//        currentActivity.runOnUiThread(new Runnable() {
//            @Override
//            public void run() {
//
//                Map jsonMap= JSON.parseObject(jsonStr);
//                final String message=(String) jsonMap.get("message");
//                if (message.equals("success")){
//                    JSONObject newFriend=(JSONObject) jsonMap.get("data");
//                    int netId=newFriend.getIntValue("id");
//                    int ownerNetId=BaseActivity.owner.getNetId();
//                    String name=newFriend.getString("name");
//                    String url=BaseActivity.SERVER_URL+newFriend.getString("imagePath");
//                    String username=newFriend.getString("username");
//                    Friend friend=new Friend(netId,username,name,url,ownerNetId);
//                    friend.save();
//                    Toast.makeText(currentActivity,"你有新的好友与消息",Toast.LENGTH_SHORT).show();
//                }
//            }
//        });
//    }
}
