package com.tofly.ghrq_route.common.ui.activity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.tofly.ghrq_route.R;
import com.tofly.ghrq_route.base.BaseApp;
import com.tofly.ghrq_route.base.ui.BaseUi;
import com.tofly.ghrq_route.base.url.NetRequestURL;
import com.tofly.ghrq_route.base.URLResponseCode;
import com.tofly.ghrq_route.common.ui.dialog.IpAddrModifyDailog;
import com.tofly.ghrq_route.module.service.NetStateService;
import com.tofly.ghrq_route.module.user.UserInfoTool;
import com.tofly.ghrq_route.module.user.controller.UserCallBack;
import com.tofly.ghrq_route.module.user.domain.UserBean;

/**
 * Created by zombiexq on 2016/6/13.
 */
public class UiSetting extends BaseUi {

    private TextView internet_tv;
    boolean mBound = false;
    NetStateService netStateService;
    private RelativeLayout setting_serverip;
    private TextView serverip;
    private TextView servernetstate;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.ui_setting);

        initView();
        initData();
        initListener();

    }

    private void initView(){
        internet_tv = (TextView) findViewById(R.id.setting_internet_tv);
        setting_serverip = (RelativeLayout) findViewById(R.id.setting_serverip);
        serverip = (TextView) findViewById(R.id.setting_serverip_tv);
        servernetstate = (TextView) findViewById(R.id.setting_servernet_tv);
    }

    private void initData(){
        /*强制进设置界面后设置端口号为8180端口*/
//        if (C.bForceSettingDefaultServerPort){
//            BaseApp.getInstance().resetIpAddr();
//        }
        servernetstate.setText("正在连接服务器");
        internet_tv.setText("查询网络状态中");
        bind();
        String ipAddr = NetRequestURL.HTTPHEAD;
        serverip.setText(ipAddr);
        //checkBackupServer();
        checkServerStatus();
    }

    private void initListener(){
        setting_serverip.setOnClickListener(v -> showIpAddrDialog());
    }

    private void showIpAddrDialog(){
        String ipAddr = NetRequestURL.HTTPHEAD;
        IpAddrModifyDailog modifyDailog = new IpAddrModifyDailog(this, ipAddr);
        modifyDailog.setClicklistener(new IpAddrModifyDailog.ClickListenerInterface() {
            @Override
            public void doOk(String addr/*, String port*/) {
                servernetstate.setTextColor(UiSetting.this.getResources().getColor(R.color.text));
                servernetstate.setText("重新连接服务器中");
                serverip.setText(addr);
                toast("设置成功");
                String mapAddr = addr.replace("xjapi", "webapitest");
                BaseApp.setIpAddrToConfig(addr, mapAddr, "");
                checkServerStatus();
            }

            @Override
            public void doCancel() {
            }
        });
        modifyDailog.show();
    }

    private void bind() {
        Intent intent = new Intent(UiSetting.this, NetStateService.class);
        bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);//通过服务中的广播获取网络状态，返回UiSetting中，显示不同的文字和文字颜色来提示用户网络状态
    }
    private void unbind() {
        if (mBound) {
            unbindService(serviceConnection);
            mBound = false;
            System.out.println("解绑service");
        }
    }

    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceDisconnected(ComponentName name) {
            mBound = false;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            netStateService = ((NetStateService.MyBinder) service)
                    .getService();
            mBound = true;
            // 添加接口实例获取连接状态
            netStateService.setOnGetConnectState(isConnected -> {
                if (isConnected) {
                    handler.sendEmptyMessage(1);

                } else {
                    handler.sendEmptyMessage(2);

                }

            });
        }
    };

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:// 已连接
                    //      Toast.makeText(UiWebView.this, "网络已经连接", Toast.LENGTH_LONG).show();
                    internet_tv.setText("网络正常");
                    internet_tv.setTextColor(UiSetting.this.getResources().getColor(R.color.text));

                    break;
                case 2:// 未连接
                    //        Toast.makeText(UiWebView.this, "网络未连接" ,Toast.LENGTH_LONG).show();
                    internet_tv.setText("网络异常");
                    internet_tv.setTextColor(UiSetting.this.getResources().getColor(R.color.red));
                    break;
                default:
                    break;
            }
        }
    };


    private void checkServerStatus(){
        UserInfoTool userInfoTool = UserInfoTool.getInstance();
        userInfoTool.userLoginTestServer(this, "", "", false, new UserCallBack(){
            @Override
            public void onLogin(boolean isSuccess, int errorCode, String errMsg, UserBean user) {
                super.onLogin(isSuccess, errorCode, errMsg, user);
                if (errorCode == URLResponseCode.ErrorCode.HTTPCONN_TIMEOUT){
                    servernetstate.setText("服务器连接异常");
                    servernetstate.setTextColor(UiSetting.this.getResources().getColor(R.color.red));
                }else if (errorCode == URLResponseCode.ErrorCode.ADDR_FOUND_FAILED){
                    servernetstate.setText("服务器地址未找到");
                    servernetstate.setTextColor(UiSetting.this.getResources().getColor(R.color.red));
                }else {
                    servernetstate.setText("服务器连接正常");
                    servernetstate.setTextColor(UiSetting.this.getResources().getColor(R.color.text));
                }
            }
        });
    }

    @Override
    protected void onDestroy()
    {
        BaseApp.cancelAllRequest(getClass().getName());
        super.onDestroy();
        unbind();
    }
}
