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.IBinder;
import android.view.Menu;
import android.view.MenuItem;
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.URLResponseCode;
import com.tofly.ghrq_route.common.util.dialog.DialogUtil;
import com.tofly.ghrq_route.module.deviceInfo.DeviceInfoTool;
import com.tofly.ghrq_route.module.gps.GpsTool;
import com.tofly.ghrq_route.module.service.NetStateService;
import com.tofly.ghrq_route.module.sign.SignTool;
import com.tofly.ghrq_route.module.sign.controller.SignCallBack;
import com.tofly.ghrq_route.module.sign.controller.SignController;
import com.tofly.ghrq_route.module.user.UserInfoTool;
import com.tofly.ghrq_route.module.user.controller.UserCallBack;
import com.tofly.ghrq_route.module.user.controller.UserController;
import com.tofly.ghrq_route.module.user.domain.UserBean;
import com.tofly.ghrq_route.common.util.EventBusUtil;
import com.tofly.ghrq_route.common.util.net.NetUtil;

import org.greenrobot.eventbus.Subscribe;

import butterknife.BindArray;
import butterknife.BindView;
import butterknife.ButterKnife;

import static com.tofly.ghrq_route.module.deviceInfo.DeviceInfoTool.DEVICEINFO_BATTERY_CHANGED;
import static com.tofly.ghrq_route.common.util.net.NetUtil.NETWORN_MOBILE;
import static com.tofly.ghrq_route.common.util.net.NetUtil.NETWORN_NONE;
import static com.tofly.ghrq_route.common.util.net.NetUtil.NETWORN_WIFI;

/**
 * Created by Amu on 2017/6/23.
 */

public class UiSystemInfo extends BaseUi {
    @BindView(R.id.text_sysinfo_user)
    TextView textSysinfoUser;
    @BindView(R.id.text_sysinfo_mobile)
    TextView textSysinfoMobile;
    @BindView(R.id.text_sysinfo_onsign)
    TextView textSysinfoOnsign;
    @BindView(R.id.text_sysinfo_offsign)
    TextView textSysinfoOffsign;
    @BindView(R.id.text_sysinfo_gps_type)
    TextView textSysinfoGpsType;
    @BindView(R.id.text_sysinfo_gps_count)
    TextView textSysinfoGpsCount;
    @BindView(R.id.text_sysinfo_gps_time)
    TextView textSysinfoGpsTime;
    @BindView(R.id.text_sysinfo_gps_radius)
    TextView textSysinfoGpsRadius;
    @BindView(R.id.text_sysinfo_max_speed)
    TextView textSysinfoMaxSpeed;
    @BindView(R.id.text_sysinfo_car_mode)
    TextView textSysinfoCarmode;
    @BindView(R.id.text_sysinfo_network_type)
    TextView textSysinfoNetworkType;
    @BindView(R.id.text_sysinfo_network_status)
    TextView textSysinfoNetworkStatus;
    @BindView(R.id.text_sysinfo_battery)
    TextView textSysinfoBattery;
    @BindView(R.id.text_sysinfo_server)
    TextView textSysinfoServer;
    @BindView(R.id.text_sysinfo_watermark)
    TextView textSysinfoWatermark;
    @BindArray(R.array.sign_status)
    String[] sign_status;

    private static final String TAG = UiSystemInfo.class.getName();

    private SignController signController;

    private UserController userController;

    private NetStateService netStateService;

    private boolean mBound = false;

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

        setContentView(R.layout.ui_system_info);
        ButterKnife.bind(this);

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

        EventBusUtil.register(this);
    }

    @Subscribe
    public void onMessageEvent(DeviceInfoTool.DeviceInfoToolEvent event) {
        if (event.message.equals(DEVICEINFO_BATTERY_CHANGED)) {
            int battery = (int) event.arg;
            textSysinfoBattery.setText(battery + "%");
        }else if (event.message.equals(DeviceInfoTool.DEVICEINFO_CONNECTION_INFO)){
            boolean isConnected = (int) event.arg == URLResponseCode.ErrorCode.SUCCESS;
            textSysinfoServer.setText(isConnected ?
                    "连接正常" : "连接异常");
            textSysinfoServer.setTextColor(isConnected ?
                    getResources().getColor(R.color.text) : getResources().getColor(R.color.colorAccent));
        }
    }

    private void initView() {

    }

    private void initData() {
        bind();
        setSystemInfo();
    }

    private void setSystemInfo(){
        UserBean userBean = BaseApp.getInstance().getLoginUser();
        if (userBean != null) {
            String userName = userBean.getUsername();
            if (userName != null && !userName.isEmpty())
                textSysinfoUser.setText(userName);

            String mobile = userBean.getMobile();
            if (mobile != null && !mobile.isEmpty())
                textSysinfoMobile.setText(mobile);
        }

        getSignStatusToday();

        DeviceInfoTool deviceInfoTool = DeviceInfoTool.getInstance();

        String gpsProvider = GpsTool.getPROVIDER();
        if (gpsProvider != null && !gpsProvider.isEmpty())
            textSysinfoGpsType.setText(gpsProvider.toUpperCase());

        if (deviceInfoTool != null) {
            int gpsCount = deviceInfoTool.getGpsStar();
            textSysinfoGpsCount.setText(gpsCount + "颗");
        }

        int timing = BaseApp.getInstance().getGpsWakeTime() / 1000; //单位s;
        textSysinfoGpsTime.setText(timing + "秒");

        int checkRadius = BaseApp.getInstance().getPointCheckRadius(); //单位米;
        textSysinfoGpsRadius.setText(checkRadius + "米");

        boolean carmode = BaseApp.getInstance().isCarMode();
        textSysinfoCarmode.setText(carmode ? R.string.yes : R.string.no);

        int checkMaxSpeed = BaseApp.getInstance().getPointMaxSpeed(); //单位米/秒;
        textSysinfoMaxSpeed.setText(checkMaxSpeed + "千米/小时");

        int isWatermark = BaseApp.getInstance().getIsPhotoWatermark(); // 图片增加水印
        textSysinfoWatermark.setText(isWatermark == 0 ? R.string.yes : R.string.no);

        /*网络连接状态*/
        int networkState = NetUtil.getNetworkState(BaseApp.getInstance());
        switch (networkState) {
            case NETWORN_NONE:
                textSysinfoNetworkType.setText("无网络");
                break;
            case NETWORN_MOBILE:
                textSysinfoNetworkType.setText("GPRS");
                break;
            case NETWORN_WIFI:
                textSysinfoNetworkType.setText("WIFI");
                break;
        }

        checkServerStatus();

        int battery = deviceInfoTool.getBatteryHealth();
        if (battery == 0){
            battery = BaseApp.getInstance().getBatteryUsage();
        }
        textSysinfoBattery.setText(battery + "%");
    }

    private void initListener() {

    }

    private void getSignStatusToday() {
        SignTool signTool = SignTool.getInstance();
        signTool.getSignStatusToday(this, new SignCallBack(){
            @Override
            public void onGetSignStatusToday(boolean isSuccess, int errorCode, String errMsg, int status, int section) {
                super.onGetSignStatusToday(isSuccess, errorCode, errMsg, status, section);
                if (isSuccess) {
                    if (status >= 0 && status < sign_status.length){
                        textSysinfoOnsign.setText(sign_status[status]);
                    }
                } else {
                    toast(errMsg);
                    DialogUtil.showTokenFailedDialog(UiSystemInfo.this, errorCode);
                }
            }
        });
    }

    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){
                    textSysinfoServer.setText("连接异常");
                    textSysinfoServer.setTextColor(getResources().getColor(R.color.red));
                }else if (errorCode == URLResponseCode.ErrorCode.ADDR_FOUND_FAILED){
                    textSysinfoServer.setText("服地址未找到");
                    textSysinfoServer.setTextColor(getResources().getColor(R.color.red));
                }else {
                    textSysinfoServer.setText("连接正常");
                    textSysinfoServer.setTextColor(getResources().getColor(R.color.text));
                }
            }
        });
    }

    private void bind() {
        Intent intent = new Intent(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(new NetStateService.GetConnectState() { // 添加接口实例获取连接状态
                @Override
                public void GetState(boolean isConnected) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            /*网络连接状态*/
                            int networkState = NetUtil.getNetworkState(BaseApp.getInstance());
                            textSysinfoNetworkStatus.setText(getResources().getString(R.string.usable));
                            textSysinfoNetworkStatus.setTextColor(getResources().getColor(R.color.text));
                            switch (networkState) {
                                case NETWORN_NONE:
                                    textSysinfoNetworkType.setText("无网络");
                                    textSysinfoNetworkStatus.setText(getResources().getString(R.string.unusable));
                                    textSysinfoNetworkStatus.setTextColor(getResources().getColor(R.color.colorAccent));
                                    break;
                                case NETWORN_MOBILE:
                                    textSysinfoNetworkType.setText("GPRS");
                                    break;
                                case NETWORN_WIFI:
                                    textSysinfoNetworkType.setText("WIFI");
                                    break;
                            }
                        }
                    });
                }
            });
        }
    };

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //getMenuInflater().inflate(R.menu.menu_server_config, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_config: {
                Intent intent = new Intent();
                intent.setClass(UiSystemInfo.this, UiSystemConfig.class);
                startActivity(intent);
            }
            break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onResume() {
        super.onResume();
        setSystemInfo();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbind();
        EventBusUtil.unregister(this);
    }
}
