package com.yidianling.uikit.business.session.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.WindowManager;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.Observer;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.MsgServiceObserve;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.CustomNotification;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.yidianling.nimbase.api.model.session.SessionCustomization;
import com.yidianling.nimbase.api.model.user.UserInfoObserver;
import com.yidianling.nimbase.business.session.constant.Extras;
import com.yidianling.nimbase.common.ui.recyclerview.adapter.BaseFetchLoadAdapter;
import com.yidianling.nimbase.common.util.log.LogUtil;
import com.yidianling.im.R;
import com.yidianling.uikit.api.NimUIKit;
import com.yidianling.uikit.business.session.fragment.YDLMessageFragment;
import com.yidianling.uikit.custom.bridge.ActionHandlerStorage;
import com.yidianling.uikit.custom.bridge.IP2PCustomActionHandler;

import java.util.List;

/**
 * 点对点聊天界面
 * <p/>
 * Created by huangjun on 2015/2/1.
 */
public class YDLP2PMessageActivity extends YDLBaseMessageActivity {

    private boolean isResume = false;
    private int screenWidth;
    private int screenHeight;
    protected YDLMessageFragment messageFragment;

    /**
     * @param context
     * @param contactId     对方id
     * @param customization 界面定制
     * @param anchor
     * @param l
     */
    public static void start(Context context, String contactId, SessionCustomization customization, IMMessage anchor, IP2PCustomActionHandler l) {
        Intent intent = new Intent();
        intent.putExtra(Extras.EXTRA_ACCOUNT, contactId);
        intent.putExtra(Extras.EXTRA_CUSTOMIZATION, customization);

        if(ActionHandlerStorage.getL(contactId) != null) {
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
        }

        ActionHandlerStorage.setL(contactId,l);

        if (anchor != null) {
            intent.putExtra(Extras.EXTRA_ANCHOR, anchor);
        }
        intent.setClass(context, YDLP2PMessageActivity.class);
        context.startActivity(intent);
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        WindowManager wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics displayMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(displayMetrics);
        screenWidth = displayMetrics.widthPixels;
        screenHeight = displayMetrics.heightPixels;
        if (ActionHandlerStorage.getL(sessionId) != null) {
            ActionHandlerStorage.getL(sessionId).clear(sessionId);
        }
        messageFragment = (YDLMessageFragment) switchContent(fragment());
        // 单聊特例话数据，包括个人信息，
        requestBuddyInfo();
        registerObservers(true);

        NIMClient.getService(MsgService.class).clearUnreadCount(sessionId, SessionTypeEnum.P2P);
    }

    @Override
    protected void onDestroy() {
        if (ActionHandlerStorage.getL(sessionId) != null)
            ActionHandlerStorage.getL(sessionId).clear(sessionId);
        //聊天返回时，检查是否有未发送内容，如果有则保存到ImTempData 临时map中，再次进入时读取
        if (messageFragment != null) {
            if (messageFragment.getInputPanel().getInputContent().equals("@")) {
                messageFragment.getInputPanel().setInputContent("");
            }
            if (ActionHandlerStorage.getL(sessionId) != null)
                ActionHandlerStorage.getL(sessionId).saveImTempData(sessionId, messageFragment.getInputPanel().getInputContent());
        }
        registerObservers(false);

        super.onDestroy();


    }

    @Override
    protected void onResume() {
        super.onResume();
        NIMClient.getService(MsgService.class).setChattingAccount(sessionId, SessionTypeEnum.P2P);
        isResume = true;

        //读取未发送的临时消息
        if (ActionHandlerStorage.getL(sessionId) != null) {
            if (messageFragment.getInputPanel().getInputContent() == null || messageFragment.getInputPanel().getInputContent().equals("")) {
                messageFragment.getInputPanel().setInputContent(ActionHandlerStorage.getL(sessionId).getImTempData(sessionId));
            }
            if (ActionHandlerStorage.needLoadNewMsg) {
                ((BaseFetchLoadAdapter.RequestFetchMoreListener)messageFragment.getMessageListPanelEx().getMessageLoder(null)).onFetchMoreRequested();
                ActionHandlerStorage.needLoadNewMsg = false;
            }
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        isResume = false;
    }

    private void requestBuddyInfo() {

        //        setTitle(UserInfoHelper.getUserTitleName(sessionId, SessionTypeEnum.P2P));
    }

    private void registerObservers(boolean register) {
        NimUIKit.getUserInfoObservable().registerObserver(userInfoObserver, register);
        NIMClient.getService(MsgServiceObserve.class).observeCustomNotification(commandObserver, register);

    }

    /**
     * 用户信息观察者
     */
    private UserInfoObserver userInfoObserver = new UserInfoObserver() {
        @Override
        public void onUserInfoChanged(List<String> accounts) {
            if (accounts.contains(sessionId)) {
                requestBuddyInfo();
            }
        }
    };

    /**
     * 命令消息接收观察者
     */
    Observer<CustomNotification> commandObserver = new Observer<CustomNotification>() {
        @Override
        public void onEvent(CustomNotification message) {
            if (!sessionId.equals(message.getSessionId()) || message.getSessionType() != SessionTypeEnum.P2P) {
                return;
            }
            showCommandMessage(message);
        }
    };

    protected void showCommandMessage(CustomNotification message) {
        if (!isResume) {
            return;
        }

        String content = message.getContent();
        try {
            JSONObject json = JSON.parseObject(content);
            int id = json.getIntValue("id");
            if (id == 1) {
                // 正在输入
                Toast.makeText(this, "对方正在输入...", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(this, "command: " + content, Toast.LENGTH_SHORT).show();
            }

        } catch (Exception e) {

        }
    }

    @Override
    protected YDLMessageFragment fragment() {
        Bundle arguments = getIntent().getExtras();
        arguments.putSerializable(Extras.EXTRA_TYPE, SessionTypeEnum.P2P);
        if (messageFragment==null){
            messageFragment = new YDLMessageFragment();
            messageFragment.setArguments(arguments);
            messageFragment.setContainerId(R.id.message_fragment_container);
        }
        return messageFragment;
    }

    @Override
    protected int getContentViewId() {
        return R.layout.im_ydl_nim_message_activity;
    }

    @Override
    protected void initToolBar() {
        setToolBar(R.id.chat_tb);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (ActionHandlerStorage.getL(sessionId) != null) {
            ActionHandlerStorage.getL(sessionId).clear(sessionId);
        }
        NIMClient.getService(MsgService.class).setChattingAccount(MsgService.MSG_CHATTING_ACCOUNT_NONE, SessionTypeEnum.None);
        //清除对应ActionHandlerStorage的方法在这边进行调用
        //而不是在YDLBaseMessageActivity的onDestroy中调用是因为ondestroy调用时机不确定，会导致第二次打开同一个activity找不到ActionHandlerStorage
        if (isFinishing()) {
            ActionHandlerStorage.recycleL(sessionId);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 45) {
            if (data != null) {
                IMMessage message = (IMMessage) data.getSerializableExtra("msg");
                LogUtil.d("TAG", "session id: " + sessionId);
                if (sessionId.equals(message.getSessionId()))
                    getYDLMessageFragment().getMessageListPanelEx().onMsgSend(message);
            }
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }
}
