package com.sobot.screencapturesdk.activity;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.media.MediaCodecInfo;
import android.media.projection.MediaProjectionManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.oray.sunlogin.bean.CodecParameter;
import com.oray.sunlogin.interfaces.IDisplayInfo;
import com.oray.sunlogin.manager.ClientSdkManager;
import com.oray.sunlogin.util.ThreadPoolManage;
import com.oray.sunlogin.utils.KnoxUtils;
import com.sobot.gson.SobotGsonUtil;
import com.sobot.network.apiUtils.SobotBaseUrl;
import com.sobot.network.apiUtils.SobotHttpUtils;
import com.sobot.network.http.HttpUtils;
import com.sobot.network.http.log.SobotNetLogUtils;
import com.sobot.screencapturesdk.R;
import com.sobot.screencapturesdk.factory.DisplayInfoFactory;
import com.sobot.screencapturesdk.module.SobotResultModule;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;

import static android.os.Build.VERSION.SDK_INT;
import static com.oray.sunlogin.util.CommandLineDesc.INPUTAGENT;
import static com.oray.sunlogin.util.CommandLineDesc.INPUTAGENT5;
import static com.oray.sunlogin.util.CommandLineDesc.SCREENAGENT;

/**
 * liboraysceen_agentn.so的运行参数：-p xxx -l xxx
 * 传递参数时，请用十进制值
 * 例如：-p 1 -l 32
 * 例如：-p 1 -l 64
 * <p>
 * -p (h264 profile type) //OMX_VIDEO_AVCPROFILETYPE
 * Constants are declared in {@link MediaCodecInfo.CodecProfileLevel}.
 * -p 的参数，请使用1
 * <p>
 * -l (h264 profile Level) //OMX_VIDEO_AVCLEVELTYPE
 * Constants are declared in {@link MediaCodecInfo.CodecProfileLevel}.
 * -l 的参数，请使用AVCLevel22（128）以下的值
 * <p>
 * liborayinput_agentn.so的运行参数：-o
 * 传递参数时，请用十进制值(0/90/180/270)
 * 例如：-o 90
 */


public class SobotHomeActivity extends Activity implements View.OnClickListener, ClientSdkManager.IAcceptListener, ClientSdkManager.IFileTransferListener {

    private static final String TAG = "SunloginClientSDK";
    private static final String LOCAL_TEMP_PATH = "/data/local/tmp/";
    /**
     * 可修改成定制后的app的沙盒路径
     */
    //private static final String APP_SANDBOXPATH = "/data/data/com.sobot.sunlogin.screencapturesdk/lib/";

    private static final String PLUGIN_NAME_DESKTOP = "desktop";
    private static final String PLUGIN_NAME_SCREENSHOT = "screenshots";
    private static final String PLUGIN_NAME_FILEMANAGER = "file";
    private static final String PLUGIN_NAME_FILETRANSFER = "filetrans";

    private Timer mTimer;

    private EditText mEditTextsessionid;
    private TextView mStatusTextView;
    private Button mLoginButton;
    private Button mLogoutButton;

    private String mAddress;

    private static final int WHAT_SHOW_TIMER = 0;
    private static final int WHAT_SHOW_STATUS = 1;
    private static final int WHAT_SHOW_TOAST = 2;

    private static final int WHAT_CREATE_SESSIONID = 4;

    private CommonHandler mHandler;
    private int totalTimes = 0;
    private boolean mCancel = false;

    private HashMap<String, String> mSessionPlugins;
    private ExecutorService mSingleExecutor = Executors.newSingleThreadExecutor();
    /**
     * app的沙盒路径，如/data/app/com.sobot.sunlogin.screencapturesdk-2/
     */
    private String mSandboxPath;
    private String defaultSandboxPath = "/data/data/com.sobot.sunlogin.screencapturesdk/lib/";

    /**
     * 申请request media projection返回的结果
     */
    private Intent mResultData;     // cache
    private MediaProjectionManager mMediaProjectionManager;
    private int REQUEST_CODE = 100;

    /**
     * 设置system权限签名的变量，ture: 需要system签名
     */
    public boolean mIsSystem = false;            //是否是system权限
    public boolean mIsUseInjectEvents = true;    //system权限远程控制下，是否使用INJECT_EVENTS权限去实现控制功能
    public boolean mIsAllowKonx = false;         //是否使用三星免root方式实现远程控制(此变量禁止直接修改，得使用Samsung Konx SDK检查)

//    public boolean mDefaultLandscape = false;    //custom
//    private final String ARG_INPUT_AGENT_LANDSCAPE = " -o 90 -a";  //custom

    private final String ARG_INPUT_AGENT = " -o 0";
    private final String ARG_SCREEN_AGENT = " -p 1 -l 128";
    private String baseurl ="chat-remote-assistance/remote-assistance";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mSessionPlugins = new HashMap<>();
        initView();
        initListener();
        initSdkManager();

        mSandboxPath = ClientSdkManager.getSandboxPath(this);
        mHandler = new CommonHandler(Looper.getMainLooper());
    }


    private void initView() {
        findViewById(R.id.tv_timer).setVisibility(View.INVISIBLE);
        mLoginButton = findViewById(R.id.btn_login);
        mLogoutButton = findViewById(R.id.btn_logout);
        mStatusTextView = findViewById(R.id.tv_status);
        mEditTextsessionid = findViewById(R.id.edit_sessionid);
    }

    private void initListener() {
        mLoginButton.setOnClickListener(this);
        mLogoutButton.setOnClickListener(this);
    }


    private void initSdkManager() {
        ClientSdkManager.getInstance().initialize(getApplicationContext(), new DisplayInfoFactory(getApplicationContext()));
        ClientSdkManager.getInstance().setCaptureListener((errorCode, message) -> {
            Message msg = mHandler.obtainMessage();
            msg.what = WHAT_SHOW_STATUS;
            msg.arg1 = errorCode;
            msg.obj = message;
            mHandler.sendMessage(msg);
        });
        ClientSdkManager.getInstance().setAcceptListener(this);
        ClientSdkManager.getInstance().setFileTransferListener(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {

            mResultData = data;
            //用户确认，开启录屏服务
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                ClientSdkManager.getInstance().stopCapture();
                ClientSdkManager.getInstance().initCapture(mResultData, mMediaProjectionManager, new DisplayInfoFactory(getApplicationContext()));
            }
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_login:
                handleLogin(mEditTextsessionid.getText().toString().trim());
                sendToast("已开始登录");
                break;
            case R.id.btn_logout:
                handleEnd();
                break;
            default:
                break;
        }
    }

    private void handleLogin(String sessionid) {
        if (TextUtils.isEmpty(sessionid)) {
            Toast.makeText(SobotHomeActivity.this, "sessionid 不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        // 更改状态提示, 并禁用登录按钮
        mStatusTextView.setText("未连接, 正在连接");
        enableLoginButton(false, false);
        Map<String, String> params = new HashMap<>();
        params.put("sessionid", sessionid);
        SobotHttpUtils.doGet(SobotHomeActivity.this, SobotBaseUrl.getApi_Host()+baseurl+"/1/sessions/" + sessionid + "/license", params, new HttpUtils.StringCallBack() {
            @Override
            public void onResponse(String result) {
                if (!TextUtils.isEmpty(result)) {
                    SobotResultModule resultModule = SobotGsonUtil.JsonToBean(result, SobotResultModule.class);
                    if (resultModule != null && !TextUtils.isEmpty(resultModule.getRetCode()) && "000000".equals(resultModule.getRetCode())) {
                        Future future = mSingleExecutor.submit(() -> {
                            if (resultModule.getItem() != null) {
                                ClientSdkManager.getInstance().loginWithLicense(resultModule.getItem().getP2pAddress(),
                                        resultModule.getItem().getLicense());
                            } else {
                                ClientSdkManager.getInstance().loginWithLicense("PHSRC://101.200.154.142:4118;PHSRC_HTTPS://101.200.154.142:3443;",
                                        "SHA1:wrxfqqap;LgvHor1h4K0EJNzOPUpvUrE5wns=");
                            }
                        });
                        try {
                            if (future.get() == null)
                                Log.i(TAG, "111111");
                        } catch (Exception e) {
                            e.printStackTrace();
                            Log.i(TAG, "Exception: " + e.getMessage());
                        }

                    } else {
                        enableLoginButton(true, false);
                        if (resultModule != null) {
                            mStatusTextView.setText("登录失败:   " + resultModule.getRetMsg());
                        }
                    }
                }
            }

            @Override
            public void onError(Exception e, String msg, int responseCode) {
                e.printStackTrace();
            }

            @Override
            public void inProgress(int progress) {

            }
        });
    }

    private void handleEnd() {
        RequestBody requestBodyJson = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), "{\n" +
                "  \"role\": \"user\", \"sessionId\": \"" + mEditTextsessionid.getText().toString().trim() + "\"\n" +
                "}");

        okhttp3.Request requestPostJson = new okhttp3.Request.Builder()
                .url(SobotBaseUrl.getApi_Host()+baseurl+"/1/sdk/end")
                .post(requestBodyJson)
                .build();

        OkHttpClient okHttpClientPostJson = new OkHttpClient();
        okHttpClientPostJson.newCall(requestPostJson).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                String message = e != null ? e.getMessage() : "";
                Log.e(TAG, "onFailure: " + message);
            }

            @Override
            public void onResponse(Call call, okhttp3.Response response) throws IOException {
                String body = response.body().string();
                SobotNetLogUtils.i(body);
                if (!TextUtils.isEmpty(body)) {
                    SobotResultModule resultModule = SobotGsonUtil.JsonToBean(body, SobotResultModule.class);
                    if (!TextUtils.isEmpty(resultModule.getRetCode()) && "000000".equals(resultModule.getRetCode())) {
                        ClientSdkManager.getInstance().stopCapture();
                        ClientSdkManager.getInstance().restoreInputMethod();
                        handleLogout();
                        sendToast("已经登出");
                    }
                }
            }
        });
    }

    private void handleLogout() {
        Future future = mSingleExecutor.submit(() -> ClientSdkManager.getInstance().logout());
        try {
            if (future.get() == null) {
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @SuppressLint("SetTextI18n")
    private void createSession(String plugin, String sessionid) {
        mAddress = ClientSdkManager.getInstance().getAddress();
        String session = ClientSdkManager.getInstance().createSession(plugin);
        mSessionPlugins.put(plugin, session);
        Log.i(TAG, "ADDRESS: " + mAddress + "\nSession: " + session);
        RequestBody requestBodyJson = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), "{\n" +
                "  \"sessionClient\": {\n" +
                "    \"clientAddress\": \"" + mAddress + "\",\n" +
                "    \"clientId\": \"" + session + "\",\n" +
                "    \"soundId\": \"\"\n" +
                "  },\n" +
                "  \"sessionId\": \"" + sessionid + "\"\n" +
                "}");

        okhttp3.Request requestPostJson = new okhttp3.Request.Builder()
                .url(SobotBaseUrl.getApi_Host()+baseurl+"/1/user/accept")
                .post(requestBodyJson)
                .build();

        OkHttpClient okHttpClientPostJson = new OkHttpClient();
        okHttpClientPostJson.newCall(requestPostJson).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, okhttp3.Response response) throws IOException {

                String body = response.body().string();
                SobotNetLogUtils.i("接受远控：" + body);
                if (!TextUtils.isEmpty(body)) {
                    SobotResultModule resultModule = SobotGsonUtil.JsonToBean(body, SobotResultModule.class);
                    if (resultModule != null) {
                        if (!TextUtils.isEmpty(resultModule.getRetCode()) && "000000".equals(resultModule.getRetCode())) {
                            SobotHomeActivity.this.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (PLUGIN_NAME_DESKTOP.compareToIgnoreCase(plugin) == 0) {
                                        if (SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                                            //开启屏幕录屏弹框
                                            startMediaProjection();
                                        }
                                        if (mIsAllowKonx) {
                                            ClientSdkManager.getInstance().setAllowKonx(mIsAllowKonx);
                                        } else if (mIsSystem && mIsUseInjectEvents) {
                                            ClientSdkManager.getInstance().setIsSystem(mIsSystem);
                                        } else if (mIsSystem) {
                                            runTaskWithSystem();
                                        } else {
                                            runTaskWithRoot();
                                        }
                                    } else if (PLUGIN_NAME_FILETRANSFER.compareToIgnoreCase(plugin) == 0) {
                                        //ClientSdkManager.getInstance().setSavePath("/sdcard/download/");
                                    }
                                }
                            });
                        } else {
                            mStatusTextView.setText("连接失败:   " + resultModule.getRetMsg());
                        }
                    }
                }
            }
        });

    }

    private void destroySession(String plugin) {
        String session = mSessionPlugins.get(plugin);
        if (!TextUtils.isEmpty(session)) {
            ClientSdkManager.getInstance().destroySession(session);
        }

        if (PLUGIN_NAME_DESKTOP.compareToIgnoreCase(plugin) == 0) {
            if (SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                //停止录屏服务
                ClientSdkManager.getInstance().stopCapture();
            }
            //还原默认输入法
            ClientSdkManager.getInstance().restoreInputMethod();
            //杀掉所有相关so
            killSdkInputProcess((!mIsSystem && !mIsAllowKonx));
        }
    }

    private void destroyAllSession() {
        for (HashMap.Entry<String, String> entry : mSessionPlugins.entrySet()) {
            String session = mSessionPlugins.get(entry.getValue());
            if (!TextUtils.isEmpty(session)) {
                ClientSdkManager.getInstance().destroySession(session);
            }
            if (PLUGIN_NAME_DESKTOP.compareToIgnoreCase(entry.getKey()) == 0) {
                if (SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    //停止录屏服务
                    ClientSdkManager.getInstance().stopCapture();
                }
                //还原默认输入法
                ClientSdkManager.getInstance().restoreInputMethod();
                //杀掉所有相关so
                killSdkInputProcess((!mIsSystem && !mIsAllowKonx));
            }
        }
    }

    /**
     * 使用root权限启动task
     */
    private void runTaskWithRoot() {
        Log.i(TAG, "runTaskWithRoot, sdk " + SDK_INT);
        //请求root权限
        ThreadPoolManage.getShortPool().execute(() -> {
            // 判断手机是否root
            if (ClientSdkManager.isRootAvailable()) {
                // 判断应用是否获得root权限
                if (ClientSdkManager.isRootPermission()) {
                    //先查杀
                    killSdkInputProcess(true);
                    //高于5.0, 21
                    if (SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        ThreadPoolManage.getShortPool().execute(() -> ClientSdkManager.LaunchExternalProcess(mSandboxPath, LOCAL_TEMP_PATH, INPUTAGENT5, getInputArgs(), true));
                    } else if (SDK_INT >= Build.VERSION_CODES.KITKAT && SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                        ThreadPoolManage.getShortPool().execute(() -> ClientSdkManager.LaunchExternalProcess(mSandboxPath, LOCAL_TEMP_PATH, INPUTAGENT, getInputArgs(), true));
                        ThreadPoolManage.getShortPool().execute(() -> ClientSdkManager.LaunchExternalProcess(defaultSandboxPath, LOCAL_TEMP_PATH, SCREENAGENT, "", true));
                    }
                    checkControlService(true);
                } else {
                    // 获取root权限失败
                    Log.i(TAG, "isRootPermission: false");
                    sendToast("isRootPermission: false");
                }
            } else {
                // 手机未root
                Log.i(TAG, "isRootAvailable: false");
                sendToast("isRootAvailable: false");
            }
        });
    }

    /**
     * 使用system权限启动task
     */
    private void runTaskWithSystem() {
        Log.i(TAG, "runTaskWithSystem, sdk " + SDK_INT);
        ThreadPoolManage.getShortPool().execute((Runnable) () -> {
            //先查杀
            killSdkInputProcess(false);
            if (SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//高于5.0, 21
                ThreadPoolManage.getShortPool().execute(() ->
                        ClientSdkManager.LaunchExternalProcess(mSandboxPath, LOCAL_TEMP_PATH, INPUTAGENT5, getInputArgs(), false));
            } else if (SDK_INT >= Build.VERSION_CODES.KITKAT && SDK_INT < Build.VERSION_CODES.LOLLIPOP) {//
                ThreadPoolManage.getShortPool().execute(() ->
                        ClientSdkManager.LaunchExternalProcess(mSandboxPath, LOCAL_TEMP_PATH, INPUTAGENT, getInputArgs(), false));
                ThreadPoolManage.getShortPool().execute(() ->
                        ClientSdkManager.LaunchExternalProcess(defaultSandboxPath, LOCAL_TEMP_PATH, SCREENAGENT, getScreenArgs(), false));
            }
            checkControlService(false);
        });
    }

    /**
     * 开启线程定时检查控制进程是否存在
     */
    private void checkControlService(final boolean bNeedRoot) {
        Log.i(TAG, "checkControlService, current root status: " + bNeedRoot);
        if (mTimer == null) {
            mTimer = new Timer();
            TimerTask timerTask = new TimerTask() {
                @Override
                public void run() {
                    String tempInputAgent;
                    if (SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        tempInputAgent = INPUTAGENT5;
                    } else {
                        tempInputAgent = INPUTAGENT;
                    }

                    boolean isInputAgentExist = ClientSdkManager.searchProcess(tempInputAgent, ClientSdkManager.FILTER_INPUTAGENT, bNeedRoot);
                    if (!isInputAgentExist && null != mTimer) {
                        Log.i(TAG, INPUTAGENT + " is not exist(1), start again...");
                        if (SDK_INT >= 21) {
                            ClientSdkManager.LaunchExternalProcess(mSandboxPath, LOCAL_TEMP_PATH, INPUTAGENT5, getInputArgs(), bNeedRoot);
                        } else if (SDK_INT >= Build.VERSION_CODES.KITKAT && SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                            ClientSdkManager.LaunchExternalProcess(mSandboxPath, LOCAL_TEMP_PATH, INPUTAGENT, getInputArgs(), bNeedRoot);
                        }
                    }
                    if (SDK_INT >= Build.VERSION_CODES.KITKAT && SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                        boolean isScreenAgentExist = ClientSdkManager.searchProcess(SCREENAGENT, ClientSdkManager.FILTER_SCREENAGENT, bNeedRoot);
                        if (!isScreenAgentExist && null != mTimer) {
                            Log.i(TAG, SCREENAGENT + " is not exist(2), start again...");
                            ClientSdkManager.LaunchExternalProcess(defaultSandboxPath, LOCAL_TEMP_PATH, SCREENAGENT, getScreenArgs(), bNeedRoot);
                        }
                    }
                }
            };
            mTimer.schedule(timerTask, 1000, 15000);
        }
    }

    /**
     * 清除input agent 进程
     *
     * @param bNeedRoot
     */
    private void killSdkInputProcess(boolean bNeedRoot) {
        Log.i(TAG, "first Kill SO, current root status: " + bNeedRoot);
        if (SDK_INT >= 21) {
            ClientSdkManager.searchAndKillProcess(INPUTAGENT5, ClientSdkManager.FILTER_INPUTAGENT, bNeedRoot);
        } else if (SDK_INT >= 19 && SDK_INT < 21) {
            ClientSdkManager.searchAndKillProcess(SCREENAGENT, ClientSdkManager.FILTER_SCREENAGENT, bNeedRoot);
            ClientSdkManager.searchAndKillProcess(INPUTAGENT, ClientSdkManager.FILTER_INPUTAGENT, bNeedRoot);
        }
    }

    /**
     * 开启获取录像弹窗
     */
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void startMediaProjection() {
        mMediaProjectionManager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);
        //可以每次都重新获取录屏权限也可以读上一次的缓存信息
        Intent captureIntent = mMediaProjectionManager.createScreenCaptureIntent();
        startActivityForResult(captureIntent, REQUEST_CODE);
    }

    /**
     * 重置编码参数
     *
     * @param displayInfo
     * @param parameter
     */
    private void resetCodecParameter(IDisplayInfo displayInfo, CodecParameter parameter) {
        ClientSdkManager.getInstance().resetCodecParameter(displayInfo, parameter);
    }

    @Override
    public void onStatusChanged(int status, int error, String extra) {
        Log.i(TAG, "call onStatusChanged, status: " + status + " !!!");
        switch (status) {
            case ClientSdkManager.IAcceptListener.STATUS_CONNECT:
                mStatusTextView.setText("已成功连接");
                enableLoginButton(false, true);
                Log.i(TAG, "extra : " + extra);
                break;
            case ClientSdkManager.IAcceptListener.STATUS_DISCONNECT:
                mStatusTextView.setText("连接已经断开");
                enableLoginButton(true, false);
//                enableSessionButton(false);
//                destroyAllSession();
                break;
            case ClientSdkManager.IAcceptListener.STATUS_LOGIN_OK:
                mStatusTextView.setText("已成功登录服务器");
                enableLoginButton(false, true);
                Message msg = mHandler.obtainMessage();
                msg.what = WHAT_CREATE_SESSIONID;
                mHandler.sendMessage(msg);
                break;
            case ClientSdkManager.IAcceptListener.STATUS_LOGIN_FAIL:
                mStatusTextView.setText("登录失败，请确认网络或appid与appkey");
                enableLoginButton(true, false);
                break;
            case ClientSdkManager.IAcceptListener.STATUS_PLUGIN_CONNECT:
                mStatusTextView.setText("插件连接成功");
                Log.i(TAG, "extra : " + extra);
                showTimer();
                break;
            case ClientSdkManager.IAcceptListener.STATUS_PLUGIN_DISCONNECT:
                mStatusTextView.setText("插件连接断开, total times: " + totalTimes);
                Log.i(TAG, "totol times: " + totalTimes);
                hideTimer();
                break;
            case ClientSdkManager.IAcceptListener.ERROR_INVALID_ARG:
                mStatusTextView.setText("无效的参数");
                enableLoginButton(true, false);
                break;
            case ClientSdkManager.IAcceptListener.ERROR_INVALID_LICENSE:
                mStatusTextView.setText("无效的授权");
                enableLoginButton(true, false);
                break;
            case ClientSdkManager.IAcceptListener.ERROR_INVALID_PROTOCOL:
                mStatusTextView.setText("无效的协议");
                enableLoginButton(true, false);
                break;
            case ClientSdkManager.IAcceptListener.ERROR_INVALID_SERVERADDR:
                mStatusTextView.setText("无效的地址");
                enableLoginButton(true, false);
                break;
            case ClientSdkManager.IAcceptListener.ERROR_LICENSE_EXPIRE:
                mStatusTextView.setText("授权已经过期");
                enableLoginButton(true, false);
                break;
            case ClientSdkManager.IAcceptListener.ERROR_LOGIN_FAIL:
                mStatusTextView.setText("登录失败");
                enableLoginButton(true, false);
                break;
            case ClientSdkManager.IAcceptListener.ERROR_VERIFY_FAIL:
                mStatusTextView.setText("appid/appkey验证失败");
                enableLoginButton(true, false);
                break;
            default:
                mStatusTextView.setText("未知错误，请确认网络或appid与appkey");
                // error case, do nothing
                enableLoginButton(true, false);
        }
    }

    @Override
    public void onNewfileArrived(int fileId) {
       /* Log.i(TAG, "fileId : " + fileId);
        FileTransferBean fileTransfer = ClientSdkManager.getInstance().getFileAttribute(fileId);
        Log.i(TAG, "fileTransfer : " + fileTransfer.toString());*/
    }

    /**
     *
     */
    private void showTimer() {
        findViewById(R.id.tv_timer).setVisibility(View.VISIBLE);
        mCancel = false;
        totalTimes = 0;
        mHandler.sendEmptyMessageDelayed(WHAT_SHOW_TIMER, 1000);
    }

    /**
     *
     */
    private void hideTimer() {
        findViewById(R.id.tv_timer).setVisibility(View.INVISIBLE);
        mCancel = true;
    }

    private void enableLoginButton(boolean blogin, boolean blogout) {
        mLoginButton.setEnabled(blogin);
        mLogoutButton.setEnabled(blogout);
    }


    private void sendToast(String message) {
        Message msg = mHandler.obtainMessage();
        msg.what = WHAT_SHOW_TOAST;
        msg.obj = message;
        mHandler.sendMessage(msg);
    }

    public class CommonHandler extends Handler {
        public CommonHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case WHAT_SHOW_TIMER:
                    TextView tvTimer = findViewById(R.id.tv_timer);
                    if (null != tvTimer) {
                        tvTimer.setText(getString(R.string.connect_time) + (++totalTimes) + getString(R.string.miao));
                    }
                    if (!mCancel) {
                        sendEmptyMessageDelayed(WHAT_SHOW_TIMER, 1000);
                    }
                    break;
                case WHAT_SHOW_STATUS:
                    TextView tvStatus = findViewById(R.id.tv_capture_status);
                    if (null != tvStatus) {
                        tvStatus.setText((CharSequence) msg.obj);
                    }
                    break;
                case WHAT_SHOW_TOAST:
                    Toast.makeText(SobotHomeActivity.this, (CharSequence) msg.obj, Toast.LENGTH_SHORT).show();
                    break;
                case WHAT_CREATE_SESSIONID:
                    createSession(PLUGIN_NAME_DESKTOP, mEditTextsessionid.getText().toString().trim());
                    break;
            }
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);//返回最新的intent
        String sessionid = getIntent().getStringExtra("sessionid");
        mEditTextsessionid.setText(sessionid);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (KnoxUtils.isSupportSamsungSdk() && KnoxUtils.checkApiLevel()) {
            boolean isActive = KnoxUtils.isAdminActive(getApplication()) && KnoxUtils.isLicenseActive(getApplication());
            mIsAllowKonx = isActive;
        }
        String sessionid = getIntent().getStringExtra("sessionId");
        mEditTextsessionid.setText(sessionid);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 在销毁时stopserver，并释放资源
        ClientSdkManager.getInstance().stopCapture();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_HOME) {
            moveTaskToBack(true);
            return true;
        } else if (keyCode == KeyEvent.KEYCODE_BACK) {
            showExitDialog();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onBackPressed() {
        mCancel = true;
        ClientSdkManager.getInstance().stopCapture();
        ClientSdkManager.getInstance().restoreInputMethod();
        handleLogout();
        killSdkInputProcess((!mIsSystem && !mIsAllowKonx));
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.exit(0);
    }


    /**
     * 启动参数
     *
     * @return
     */
    private String getScreenArgs() {
        return ARG_SCREEN_AGENT;
    }

    /**
     * 启动参数
     *
     * @return
     */
    private String getInputArgs() {
        return ARG_INPUT_AGENT;
    }

    public void showExitDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.app_name)
                .setMessage("是否退出应用")
                .setPositiveButton("确定", (dialog, which) -> {
                    Toast.makeText(SobotHomeActivity.this, "点击了确定", Toast.LENGTH_SHORT).show();
                    System.exit(0);
                })
                .setNegativeButton("取消", null);
        AlertDialog alertDialog = builder.create();
        alertDialog.show();
    }
}
