package com.tofly.ghrq_route.module.systemConfig;

import android.content.Context;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.mgq.base.utils.toast.ToastUtil;
import com.tofly.ghrq_route.R;
import com.tofly.ghrq_route.base.BaseApp;
import com.tofly.ghrq_route.base.C;
import com.tofly.ghrq_route.module.sqlite.DBDaoHelper;
import com.tofly.ghrq_route.module.systemConfig.controller.ServerSysConfigCallBack;
import com.tofly.ghrq_route.module.systemConfig.controller.ServerSysConfigController;
import com.tofly.ghrq_route.module.systemConfig.domain.ServerParamConfigBean;
import com.tofly.ghrq_route.module.systemConfig.domain.ServerSysConfigBean;
import com.tofly.ghrq_route.module.systemConfig.domain.SystemConfigBean;
import com.tofly.ghrq_route.module.systemConfig.domain.SystemConfigEvent;
import com.tofly.ghrq_route.module.user.domain.UserBean;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

/**
 * Created by Amu on 2017/4/26.
 */

public class SystemConfigTool {

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

    private static SystemConfigTool systemConfigTool = null;

    private DBDaoHelper dbDaoHelper;

    private ServerSysConfigController sysConfigController;

    private boolean isFirstCheck = true;

    private SystemConfigTool() {
        dbDaoHelper = DBDaoHelper.getInstance();
    }

    public static synchronized SystemConfigTool getInstance() {
        if (systemConfigTool == null) {
            systemConfigTool = new SystemConfigTool();
        }
        return systemConfigTool;
    }

    public void checkConfigUpdate(final Context context) {
        UserBean userBean = BaseApp.getInstance().getLoginUser();
        if (userBean != null) {
            if (sysConfigController == null)
                sysConfigController = new ServerSysConfigController(context);
            sysConfigController.getSysSetting(context, new ServerSysConfigCallBack() {
                @Override
                public void onGetSysSetting(boolean isSuccess, int errorCode, String errMsg, JsonObject settings) {
                    super.onGetSysSetting(isSuccess, errorCode, errMsg, settings);
                    if (isSuccess) {
                        boolean isNeedUpdate = checkIsNeedUpdate(settings);
                        if (isNeedUpdate) {
                            EventBus.getDefault().post(new SystemConfigEvent(SystemConfigEvent.SYSTEM_CONFIG_CHANGED, null));
                        }
                    } else {
                        errMsg = BaseApp.formatErrorMessage(errorCode, errMsg);
                        ToastUtil.showToast(context, errMsg);
                    }
                }
            });
        }
    }

    private boolean checkIsNeedUpdate(JsonObject settings) {
        if (settings != null) {
            String key = SystemConfigBean.SERVER_UPRATE_KEY;
            if (settings.has(key)) {
                JsonElement jsonUprate = settings.get(key);
                String server_uprate = jsonUprate.getAsString();
                SystemConfigBean uprateConfig = BaseApp.getSystemConfigUprate();
                if (uprateConfig != null) {
                    String value = uprateConfig.getValue();
                    if (value != null) {
                        if (!value.equals(server_uprate)) {
                            return true;
                        }
                    }
                }
            }
            key = SystemConfigBean.SERVER_REFRESH_KEY;
            if (settings.has(key)) {
                JsonElement jsonRefresh = settings.get(key);
                String server_refresh = jsonRefresh.getAsString();
                SystemConfigBean refreshConfig = BaseApp.getSystemConfigRefresh();
                if (refreshConfig != null) {
                    String value = refreshConfig.getValue();
                    if (value != null) {
                        if (!value.equals(server_refresh)) {
                            return true;
                        }
                    }
                }
            }
            key = SystemConfigBean.SERVER_RADIUS_KEY;
            if (settings.has(key)) {
                JsonElement jsonRadius = settings.get(key);
                String server_radius = jsonRadius.getAsString();
                SystemConfigBean radiusConfig = BaseApp.getSystemConfigRadius();
                if (radiusConfig != null) {
                    String value = radiusConfig.getValue();
                    if (value != null) {
                        if (!value.equals(server_radius)) {
                            return true;
                        }
                    }
                }
            }
            key = SystemConfigBean.SERVER_RADIUS_DEVICE_KEY;
            if (settings.has(key)) {
                JsonElement jsonRadius = settings.get(key);
                String server_radius_device = jsonRadius.getAsString();
                SystemConfigBean radiusConfig = BaseApp.getSystemConfigRadiusDevice();
                if (radiusConfig != null) {
                    String value = radiusConfig.getValue();
                    if (value != null) {
                        if (!value.equals(server_radius_device)) {
                            return true;
                        }
                    }
                }
            }
/*            key = SystemConfigBean.SERVER_UPRATE_CAR_KEY;
            if (settings.has(key)) {
                JsonElement jsonUprate = settings.get(key);
                String server_uprate_car = jsonUprate.getAsString();
                SystemConfigBean carUprateConfig = BaseApp.getSystemConfigUprateCar();
                if (carUprateConfig != null) {
                    String value = carUprateConfig.getValue();
                    if (value != null) {
                        if (!value.equals(server_uprate_car)) {
                            return true;
                        }
                    }
                }
            }*/
            key = SystemConfigBean.SERVER_RADIUS_CAR_KEY;
            if (settings.has(key)) {
                JsonElement jsonRadius = settings.get(key);
                String server_radius_car = jsonRadius.getAsString();
                SystemConfigBean carRadiusConfig = BaseApp.getSystemConfigRadiusCar();
                if (carRadiusConfig != null) {
                    String value = carRadiusConfig.getValue();
                    if (value != null) {
                        if (!value.equals(server_radius_car)) {
                            return true;
                        }
                    }
                }
            }
            key = SystemConfigBean.SERVER_MAX_SPEED_KEY;
            if (settings.has(key)) {
                JsonElement jsonSpeed = settings.get(key);
                String server_max_speed = jsonSpeed.getAsString();
                SystemConfigBean maxSpeedConfig = BaseApp.getSystemConfigMaxSpeed();
                if (maxSpeedConfig != null) {
                    String value = maxSpeedConfig.getValue();
                    if (value != null) {
                        if (!value.equals(server_max_speed)) {
                            return true;
                        }
                    }
                }
            }
            key = SystemConfigBean.SERVER_MAX_SPEED_CAR_KEY;
            if (settings.has(key)) {
                JsonElement jsonSpeed = settings.get(key);
                String server_max_speed_car = jsonSpeed.getAsString();
                SystemConfigBean carMaxSpeedConfig = BaseApp.getSystemConfigMaxSpeedCar();
                if (carMaxSpeedConfig != null) {
                    String value = carMaxSpeedConfig.getValue();
                    if (value != null) {
                        if (!value.equals(server_max_speed_car)) {
                            return true;
                        }
                    }
                }
            }
/*            key = SystemConfigBean.SERVER_BUILD_RANGE_KEY;
            if (settings.has(key)) {
                JsonElement jsonRadius = settings.get(key);
                String server_build_range = jsonRadius.getAsString();
                SystemConfigBean buildRangeConfig = BaseApp.getSystemConfigBuildRange();
                if (buildRangeConfig != null) {
                    String value = buildRangeConfig.getValue();
                    if (value != null) {
                        if (!value.equals(server_build_range)) {
                            return true;
                        }
                    }
                }
            }*/
            key = SystemConfigBean.SERVER_MAX_GPS_PRECISION_KEY;
            if (settings.has(key)) {
                JsonElement jsonPrecision = settings.get(key);
                String server_gps_precision = jsonPrecision.getAsString();
                SystemConfigBean gpsPrecisionConfig = BaseApp.getSystemConfigMaxGpsPrecision();
                if (gpsPrecisionConfig != null) {
                    String value = gpsPrecisionConfig.getValue();
                    if (value != null) {
                        if (!value.equals(server_gps_precision)) {
                            return true;
                        }
                    }
                }
            }
            key = SystemConfigBean.SERVER_MAX_GPS_SPEED_KEY;
            if (settings.has(key)) {
                JsonElement jsonMaxGpsSpeed = settings.get(key);
                String server_max_gps_speed = jsonMaxGpsSpeed.getAsString();
                SystemConfigBean maxGpsSpeedConfig = BaseApp.getSystemConfigMaxGpsSpeed();
                if (maxGpsSpeedConfig != null) {
                    String value = maxGpsSpeedConfig.getValue();
                    if (value != null) {
                        if (!value.equals(server_max_gps_speed)) {
                            return true;
                        }
                    }
                }
            }
            key = SystemConfigBean.SERVER_PHOTO_WATERMARK_KEY;
            if (settings.has(key)) {
                JsonElement jsonPhotoWatermark = settings.get(key);
                String server_photo_watermark = jsonPhotoWatermark.getAsString();
                SystemConfigBean photoWatermarkConfig = BaseApp.getSystemConfigPhotoWatermark();
                if (photoWatermarkConfig != null) {
                    String value = photoWatermarkConfig.getValue();
                    if (value != null) {
                        if (!value.equals(server_photo_watermark)) {
                            return true;
                        }
                    }
                }
            }
        }
        return false;
    }

    public void updateServerConfig(final Context context) {

        UserBean userBean = BaseApp.getInstance().getLoginUser();
        if (userBean == null)
            return;
        if (sysConfigController == null)
            sysConfigController = new ServerSysConfigController(context);
        sysConfigController.getSysSetting(context, new ServerSysConfigCallBack() {
            @Override
            public void onGetSysSetting(boolean isSuccess, int errorCode, String errMsg, JsonObject settings) {
                super.onGetSysSetting(isSuccess, errorCode, errMsg, settings);
                if (isSuccess) {
                    if (settings != null) {
                        String server_addr = "";
                        String server_port = "";
                        String server_uprate = "";
                        String server_refresh = "";
                        String server_radius = "";
                        String server_radius_device = "";
                        String server_uprate_car = "";
                        String server_radius_car = "";
                        String server_build_range = "";
                        String server_speed = "";
                        String server_speed_car = "";
                        String server_gps_precision = "";
                        String server_max_gps_speed = "";
                        String server_photo_watermark = "";

                        ServerParamConfigBean paramConfigBean = new ServerParamConfigBean();
                        String key = SystemConfigBean.SERVER_ADDR_KEY;
                        String desc = SystemConfigBean.SERVER_ADDR_DESC;
                        String serverip_key = SystemConfigBean.SERVER_ADDR_KEY;
                        if (settings.has(serverip_key) && settings.get(serverip_key) != null) {
                            JsonElement jsonAddr = settings.get(serverip_key);
                            server_addr = jsonAddr.getAsString();

                            //updateDatabase(key, server_addr, desc);
                        }
//                        key = SystemConfigBean.SERVER_PORT_KEY;
//                        desc = SystemConfigBean.SERVER_PORT_DESC;
//                        if (settings.has(key)) {
//                            JsonElement jsonPort = settings.get(key);
//                            if (!jsonPort.isJsonNull()) {
//                                server_port = jsonPort.getAsString();
//
//                                updateDatabase(key, server_port, desc);
//                            }
//                        }
                        key = SystemConfigBean.SERVER_UPRATE_KEY;
                        desc = SystemConfigBean.SERVER_UPRATE_DESC;
                        if (settings.has(key) && settings.get(key) != null) {
                            JsonElement jsonUprate = settings.get(key);
                            server_uprate = jsonUprate.getAsString();
                            paramConfigBean.setUploadRate(server_uprate);

                            //updateDatabase(key, server_uprate, desc);
                        }
                        key = SystemConfigBean.SERVER_REFRESH_KEY;
                        desc = SystemConfigBean.SERVER_REFRESH_DESC;
                        if (settings.has(key) && settings.get(key) != null) {
                            JsonElement jsonRefresh = settings.get(key);
                            server_refresh = jsonRefresh.getAsString();
                            paramConfigBean.setRefreshInternal(server_refresh);

                            //updateDatabase(key, server_uprate, desc);
                        }
                        key = SystemConfigBean.SERVER_RADIUS_KEY;
                        desc = SystemConfigBean.SERVER_RADIUS_DESC;
                        if (settings.has(key) && settings.get(key) != null) {
                            JsonElement jsonRadius = settings.get(key);
                            server_radius = jsonRadius.getAsString();
                            paramConfigBean.setMinDistanceInPlace(server_radius);

                            //updateDatabase(key, server_radius, desc);
                        }
                        key = SystemConfigBean.SERVER_RADIUS_DEVICE_KEY;
                        desc = SystemConfigBean.SERVER_RADIUS_DEVICE_DESC;
                        if (settings.has(key) && settings.get(key) != null) {
                            JsonElement jsonRadius = settings.get(key);
                            server_radius_device = jsonRadius.getAsString();
                            paramConfigBean.setMinDistanceInDevice(server_radius_device);

                            //updateDatabase(key, server_radius, desc);
                        }
//                        key = SystemConfigBean.SERVER_UPRATE_CAR_KEY;
//                        desc = SystemConfigBean.SERVER_UPRATE_CAR_DESC;
//                        if (settings.has(key)) {
//                            JsonElement jsonUprate = settings.get(key);
//                            server_uprate_car = jsonUprate.getAsString();
//                            paramConfigBean.setUprate_car(server_uprate_car);
//
//                            updateDatabase(key, server_uprate_car, desc);
//                        }
                        key = SystemConfigBean.SERVER_RADIUS_CAR_KEY;
                        desc = SystemConfigBean.SERVER_RADIUS_CAR_DESC;
                        if (settings.has(key) && settings.get(key) != null) {
                            JsonElement jsonRadius = settings.get(key);
                            server_radius_car = jsonRadius.getAsString();
                            paramConfigBean.setCarMinDistanceInPlace(server_radius_car);

                            //updateDatabase(key, server_radius_car, desc);
                        }
/*                        key = SystemConfigBean.SERVER_BUILD_RANGE_KEY;
                        desc = SystemConfigBean.SERVER_BUILD_RANGE_DESC;
                        if (settings.has(key) && settings.get(key) != null) {
                            JsonElement jsonRadius = settings.get(key);
                            server_build_range = jsonRadius.getAsString();
                            paramConfigBean.setBuildRange(server_build_range);

                            updateDatabase(key, server_build_range, desc);
                        }*/
                        key = SystemConfigBean.SERVER_MAX_SPEED_KEY;
                        desc = SystemConfigBean.SERVER_MAX_SPPED_DESC;
                        if (settings.has(key) && settings.get(key) != null) {
                            JsonElement jsonSpeed = settings.get(key);
                            server_speed = jsonSpeed.getAsString();
                            paramConfigBean.setMaxSpeed(server_speed);

                            //updateDatabase(key, server_speed, desc);
                        }
                        key = SystemConfigBean.SERVER_MAX_SPEED_CAR_KEY;
                        desc = SystemConfigBean.SERVER_MAX_SPPED_CAR_DESC;
                        if (settings.has(key) && settings.get(key) != null) {
                            JsonElement jsonSpeedCar = settings.get(key);
                            server_speed_car = jsonSpeedCar.getAsString();
                            paramConfigBean.setCarMaxSpeed(server_speed_car);

                            //updateDatabase(key, server_speed_car, desc);
                        }
                        key = SystemConfigBean.SERVER_MAX_GPS_PRECISION_KEY;
                        desc = SystemConfigBean.SERVER_MAX_GPS_PRECISION_DESC;
                        if (settings.has(key) && settings.get(key) != null) {
                            JsonElement jsonGpsPrecision = settings.get(key);
                            server_gps_precision = jsonGpsPrecision.getAsString();
                            paramConfigBean.setTrackMaxAccuracy(server_gps_precision);

                            //updateDatabase(key, server_gps_precision, desc);
                        }
                        key = SystemConfigBean.SERVER_MAX_GPS_SPEED_KEY;
                        desc = SystemConfigBean.SERVER_MAX_GPS_SPEED_DESC;
                        if (settings.has(key) && settings.get(key) != null) {
                            JsonElement jsonMaxGpsSpeed = settings.get(key);
                            server_max_gps_speed = jsonMaxGpsSpeed.getAsString();
                            paramConfigBean.setTrackMaxSpeed(server_max_gps_speed);

                            //updateDatabase(key, server_max_gps_speed, desc);
                        }
                        key = SystemConfigBean.SERVER_PHOTO_WATERMARK_KEY;
                        desc = SystemConfigBean.SERVER_PHOTO_WATERMARK_DESC;
                        if (settings.has(key) && settings.get(key) != null) {
                            JsonElement jsonPhotoWatermark = settings.get(key);
                            server_photo_watermark = jsonPhotoWatermark.getAsString();
                            paramConfigBean.setImageWatermark(server_photo_watermark);

                            //updateDatabase(key, server_photo_watermark, desc);
                        }

                        setLocalUprateRadius(paramConfigBean);
                        //checkServerAddr(server_addr, server_port);
                    }
                } else {
                    ToastUtil.showToast(context, errMsg);
                }
            }
        });
    }

    private void updateDatabase(String key, String value, String desc) {
        if (key != null && !key.isEmpty() &&
                value != null && !value.isEmpty()) {
            SystemConfigBean systemConfigBean = new SystemConfigBean();
            systemConfigBean.setCode(key);
            systemConfigBean.setValue(value);
            if (desc != null && !desc.isEmpty()) {
                systemConfigBean.setDesc(desc);
            }
            dbDaoHelper.insertOrUpdateSysConfig(systemConfigBean);
        }
    }

    private void setLocalUprateRadius(ServerParamConfigBean paramConfigBean) {
        BaseApp.getInstance().setUprateRaidusToConfig(paramConfigBean);
    }

    public void getPhotoTypeConfigList(final Context context, final ServerSysConfigCallBack sysConfigCallBack) {
        UserBean userBean = BaseApp.getInstance().getLoginUser();
        if (sysConfigController == null)
            sysConfigController = new ServerSysConfigController(context);
        sysConfigController.getPhotoTypeConfigList(userBean.getToken(), 1, C.DEFAULT_MAX_LOAD_PAGESIZE, new ServerSysConfigCallBack() {
            @Override
            public void onGetSysConfigList(boolean isSuccess, int errorCode, String errMsg, List<ServerSysConfigBean> configs, int total) {
                super.onGetSysConfigList(isSuccess, errorCode, errMsg, configs, total);
                if (isSuccess) {
                } else {
                    errMsg = BaseApp.formatErrorMessage(errorCode, errMsg);
                    String strWarn = context.getString(R.string.photoreport_get_phototype_err) + errMsg;
                    ToastUtil.showToast(context, strWarn);
                }

                if (sysConfigCallBack != null)
                    sysConfigCallBack.onGetSysConfigList(isSuccess, errorCode, errMsg, configs, total);
            }
        });
    }

    public void uploadLocalSystemLogFiles(Context context, List<String> files, final ServerSysConfigCallBack sysConfigCallBack) {
        if (sysConfigController == null)
            sysConfigController = new ServerSysConfigController(context);
        sysConfigController.uploadLocalSystemLogFiles(context, files, new ServerSysConfigCallBack() {
            @Override
            public void onUploadLocalSystemLogFiles(boolean isSuccess, int errorCode, String errMsg) {
                super.onUploadLocalSystemLogFiles(isSuccess, errorCode, errMsg);
                String strWarn = context.getString(R.string.log_upload_upload_ok);
                if (isSuccess) {
                } else {
                    errMsg = BaseApp.formatErrorMessage(errorCode, errMsg);
                    strWarn = context.getString(R.string.log_upload_upload_error) + errMsg;
                }
                ToastUtil.showToast(context, strWarn);

                if (sysConfigCallBack != null)
                    sysConfigCallBack.onUploadLocalSystemLogFiles(isSuccess, errorCode, errMsg);
            }
        });
    }
}
