package kr.co.icontrols.ilp300_700.screen;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.ParcelFileDescriptor;
import android.text.TextUtils;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.orhanobut.logger.Logger;
import com.sensetime.demo.SenseTimeApp;
import com.sensetime.demo.SenseTimeMtc;
import com.sensetime.demo.ui.BaseActivity;
import com.sensetime.demo.util.AppUtils;
import com.sensetime.demo.util.FileUtils;
import com.sensetime.demo.util.MaterialDialogUtils;
import com.sensetime.demo.util.Util;
import com.sensetime.mtc.AiConfig;
import com.sensetime.mtc.MClient;
import com.sensetime.mtc.MtcCallback;
import com.sensetime.mtc.MtcCode;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import kr.co.icontrols.ilp300_700.MainActivity;
import kr.co.icontrols.ilp300_700.R;


public class SettingActivity extends BaseActivity {

    public static final int SELECT_IMG_VERIFY = 1001;
    public static final int SELECT_IMG_STATIC_RECOGNIZE = 1002;

    private static final int UPGRADE_FIRMWARE = 42;//whatever number
    private MClient mClient = MClient.getInstance();

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Logger.d("onCreate");

//        try {
//            Thread.sleep(1000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//
//

        Handler mHandler = new Handler();
        mHandler.postDelayed(new Runnable()  {
            public void run() {
                // 시간 지난 후 실행할 코딩
                upgradeFirmwareBtnListener();
            }
        }, 5000); // 0.5초후
    }

    @Override
    protected void initView() {
        setContentView(R.layout.activity_setting);
        TextView textView = (TextView) findViewById(R.id.setting_app_version_view);
        String info =
                AppUtils.getAppName(getApplicationContext()) + " : " + AppUtils.getVerionName(getApplicationContext()) + "\n Build code:" + AppUtils.getVerionCode(getApplicationContext());
        textView.setText(info);


    }

    @Override
    protected void initData() {
        if (SenseTimeMtc.M10 == SenseTimeMtc.getInstance().getmDeviceModule()) {//M10 not exist brightness sensor
            Button deviceBrightnessBtn = (Button) findViewById(R.id.setting_device_brightness_sensor_get_btn);
            deviceBrightnessBtn.setVisibility(View.GONE);
        }


    }

    @Override
    protected void onStop() {
        super.onStop();
        Logger.d("onStop");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Logger.d("onDestroy");
    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.setting_del_user_btn:
                MaterialDialogUtils.showInputDialog(this, getString(R.string.setting_btn_del_user), "")
                        .input("id", "", (@NonNull MaterialDialog dialog, CharSequence input) -> {
                        })
                        .onPositive((@NonNull MaterialDialog dialog, @NonNull DialogAction which) -> {
                            String id = dialog.getInputEditText().getText().toString();
                            mClient.mtcAiDelUserImageById(id, (mtcCode, result) -> {

                                if (mtcCode == MtcCode.SUCCESS) {
                                    showToast(R.string.notice_success);
                                } else {
                                    showToast(getMtcErrorMsg(mtcCode));
                                }
                            });

                        })
                        .show();
                break;
            case R.id.setting_del_all_user_btn:
                MaterialDialogUtils.showBasicDialog(this, getString(R.string.setting_btn_batch_del_user), "")
                        .onPositive((@NonNull MaterialDialog dialog, @NonNull DialogAction which) -> {
                            mClient.mtcAiClearAllImage((mtcCode, result) -> {
                                if (mtcCode == MtcCode.SUCCESS) {
                                    showToast(R.string.notice_success);
                                } else {
                                    showToast(getMtcErrorMsg(mtcCode));
                                }
                            });

                        })
                        .show();
                break;
            case R.id.setting_batch_add_user_btn:

                break;
            case R.id.setting_upgrade_firmware_btn:
                upgradeFirmwareBtnListener();
                break;
            case R.id.setting_device_info_btn:
                mClient.mtcSystemVersionInfoGet((mtcCode, result) ->
                        showBasicDialogNoCancel(R.string.setting_btn_device_info, "" + result));
                break;
            case R.id.quantity_of_id_btn:
                getCountOfId();
                break;
        }
    }

    @SuppressLint("CheckResult")
    private void getCountOfId() {
        mClient.mtcAiIDCountGet((mtcCode, result) -> {
            if (mtcCode == MtcCode.SUCCESS && !TextUtils.isEmpty(result)) {
                int idCount = Integer.parseInt(result);
                showBasicDialogNoCancel(R.string.quantity_of_id, idCount + "");
            } else {
                showToast(getMtcErrorMsg(mtcCode));
            }
        });
    }


    private void faceRecognizeOneToOne() {
//        MaterialDialog materialDialog = MaterialDialogUtils.showCustomDialog(this, "1:1", R.layout.recognize_1_1_dialog).build();
//        View customView = materialDialog.getCustomView();
//        EditText idEt = (EditText) customView.findViewById(R.id.id_et);
//        RadioGroup verify_1_1_rg = (RadioGroup) customView.findViewById(R.id.recognize_1_1_rg);
//        if (SenseTimeMtc.M10 == SenseTimeMtc.getInstance().getmDeviceModule() && AiConfig.getInstance().getRecognizeMode() == 0) {
//            //M10默认不支持活体识别，除非AiConfig里的recognizeMode的值等于1，也就是手动开启了活体识别
//            customView.findViewById(R.id.single_face_open_liveness_1_1_rb).setVisibility(View.GONE);
//            customView.findViewById(R.id.multi_face_open_liveness_1_1_rb).setVisibility(View.GONE);
//        }
//        verify_1_1_rg.check(R.id.single_face_1_1_rb);
//
//        materialDialog.getBuilder().onPositive((dialog, which) -> {
//            String id = idEt.getText().toString();
//            if (TextUtils.isEmpty(id)) {
//                showToast(R.string.input_id);
//                return;
//            }
//            SenseTimeApp senseTimeApp = (SenseTimeApp) getApplication();
//            String imgPath = senseTimeApp.getSelectedImagePaths().valueAt(0);
//            byte[] data = FileUtils.read(imgPath);
//            int checkedId = verify_1_1_rg.getCheckedRadioButtonId();
//
//            int reco_mode = 0x00;
//            int face_mode = 0x00;
//
//            if (checkedId == R.id.single_face_1_1_rb) {
//                reco_mode = 0x00;
//                face_mode = 0x00;
//            } else if (checkedId == R.id.multi_face_1_1_rb) {
//                reco_mode = 0x00;
//                face_mode = 0x01;
//            } else if (checkedId == R.id.single_face_open_liveness_1_1_rb) {
//                reco_mode = 0x01;
//                face_mode = 0x00;
//            } else if (checkedId == R.id.multi_face_open_liveness_1_1_rb) {
//                reco_mode = 0x01;
//                face_mode = 0x01;
//            }
//            MaterialDialog progressDialog = MaterialDialogUtils.showIndeterminateProgressDialog(SettingActivity.this, "", false).show();
//            MClient.getInstance().mtcAiStartVerify(reco_mode, face_mode, data, id, (mtcCode, result) -> {
//                if (progressDialog != null) {
//                    progressDialog.dismiss();
//                }
//                if (mtcCode == MtcCode.SUCCESS) {
//                    showToast(R.string.notice_success);
//                } else {
//                    showToast(getMtcErrorMsg(mtcCode));
//                }
//            });
//
//        });
//        materialDialog.show();
    }


    private void imageAdd() {
//        SenseTimeApp senseTimeApp = (SenseTimeApp) getApplication();
//        int imgCount = senseTimeApp.getSelectedImagePaths().size();
//        MaterialDialog.Builder builder = MaterialDialogUtils.showCustomDialog(this, getString(R.string.select_item_num) + imgCount, R.layout.input_image_dialog);
//        View view = builder.build().getView();
//        EditText userIdEt = (EditText) view.findViewById(R.id.user_id_et);
//        if (imgCount > 1) {
//            userIdEt.setVisibility(View.GONE);
//        }
//        builder.onPositive((dialog, which) -> {
//            String userId = "";
//            if (imgCount == 1) {
//                userId = userIdEt.getText().toString();
//            }
//            MulitiImgTask mulitiImgTask = new MulitiImgTask(this, imgCount, userId);
//            mulitiImgTask.execute();
//        });
//        builder.show();
    }


    private int applyAddImage(String path, String id) {
        byte[] data = FileUtils.read(path);
        int ret = MtcCode.ERR_NO_IMAGE.getRetCode();
        if (data != null) {
//            ret = mClient.mtcAiAddImageFromExternal(data, id);
            ret = mClient.mtcAiAddLargeImageFromExternal(data, id);// 大图片接口
        }
        return ret;
    }

    @SuppressLint("CheckResult")
    public void getAllIds(View v) {
        MaterialDialog progressDialog = MaterialDialogUtils.showIndeterminateProgressDialog(this, "", false).show();
        mClient.mtcAllIdListGet((mtcCode, result) -> {

            if (mtcCode == MtcCode.SUCCESS) {
                Logger.d("result:" + result);
                MaterialDialogUtils.showBasicDialogNoCancel(this, getString(R.string.get_all_ids), result).show();
            }
            progressDialog.dismiss();
        });
    }

    public void queryID(View v) {
        MaterialDialogUtils.showInputDialog(this, getString(R.string.id_is_in_library), "")
                .input("id", "", (@NonNull MaterialDialog dialog, CharSequence input) -> {
                })
                .onPositive((@NonNull MaterialDialog dialog, @NonNull DialogAction which) -> {
                    String id = dialog.getInputEditText().getText().toString();
                    MClient.getInstance().mtcAiQueryId(id, (mtcCode, result) -> {

                        if (mtcCode == MtcCode.SUCCESS && !TextUtils.isEmpty(result)) {
                            int idIsExist = Integer.parseInt(result);
                            if (idIsExist == 0) {
                                showToast(R.string.id_is_exist);
                            } else {
                                showToast(R.string.id_is_not_exist);
                            }
                        } else {
                            showToast(getMtcErrorMsg(mtcCode));
                        }
                    });

                })
                .show();
    }

    public void verify_1_1(View v) {
//        Intent staticContrastIntent = new Intent(this, ImageSelectorActivity.class);
//        staticContrastIntent.putExtra(ImageSelectorActivity.WILL_SELECT_IMG_NUM, 1);
//        startActivityForResult(staticContrastIntent, SELECT_IMG_VERIFY);
    }

    public void staticVerify(View v) {
//        Intent staticContrastIntent = new Intent(this, ImageSelectorActivity.class);
//        staticContrastIntent.putExtra(ImageSelectorActivity.WILL_SELECT_IMG_NUM, 1);
//        startActivityForResult(staticContrastIntent, SELECT_IMG_STATIC_RECOGNIZE);
    }

    public void recoStatusGet(View v) {
        mClient.mtcAiStatusGet((mtcCode, result) -> {

            if (mtcCode == MtcCode.SUCCESS && !TextUtils.isEmpty(result)) {
                String recoStatus = "";
                int recognizeStatus = Integer.parseInt(result);
                if (recognizeStatus == 0) {
                    recoStatus = getString(R.string.main_btn_pause_recog);
                } else if (recognizeStatus == 1) {
                    recoStatus = getString(R.string.main_btn_recognize);
                } else {
                    recoStatus = getString(R.string.notice_failure);
                }
                showBasicDialogNoCancel(R.string.check_recognition_status, recoStatus);
            } else {
                showToast(getMtcErrorMsg(mtcCode));
            }
        });
    }

    public void rebootSystem(View v) {
        List<String> rebootTips = new ArrayList<>();
        rebootTips.add(getString(R.string.reboot)); // 直接重启
        rebootTips.add(getString(R.string.u_user_reboot)); //切U盘用户模式重启
        rebootTips.add(getString(R.string.none_u_user_reboot)); //非U盘用户模式重启
        rebootTips.add(getString(R.string.u_factory_reboot)); //切U盘工厂模式重启
        rebootTips.add(getString(R.string.none_factory_reboot)); //非U盘工厂模式重启

        List<Integer> rebootCommand = new ArrayList<>();
        rebootCommand.add(0x00); // 直接重启
        rebootCommand.add(0x01); //切U盘用户模式重启
        rebootCommand.add(0x02); //非U盘用户模式重启
        rebootCommand.add(0x03); //切U盘工厂模式重启
        rebootCommand.add(0x04); //非U盘工厂模式重启
        int selectedIndex = 0;
        MaterialDialogUtils.showSingleListDialog(this, getString(R.string.reboot_system) + ",  " + getString(R.string.need_reboot_app), rebootTips, selectedIndex)
                .onPositive((@NonNull MaterialDialog dialog, @NonNull DialogAction which) -> {
                    int selectIndex = dialog.getSelectedIndex();
                    mClient.mtcSystemReboot(new MtcCallback() {
                        @Override
                        public void onResult(MtcCode mtcCode, String result) {
                            if (mtcCode == MtcCode.SUCCESS) {
                                showToast(R.string.notice_success);
                            } else {
                                showToast(getMtcErrorMsg(mtcCode));
                            }
                        }
                    });

                }).show();
    }

    public void factoryReset(View v) {
        List<String> factoryResetList = new ArrayList<>();
        factoryResetList.add(getString(R.string.clear_user_configuration));
//        factoryResetList.add(getString(R.string.save_user_configuration)); //恢复出厂设置并且保留地库，暂时模组未实现
        int selectedIndex = 0;

        MaterialDialogUtils.showSingleListDialog(this, getResources().getString(R.string.factory_reset), factoryResetList, selectedIndex)
                .onPositive((@NonNull MaterialDialog dialog, @NonNull DialogAction which) -> {
                    int selectIndex = dialog.getSelectedIndex();
                    int mode;
                    if (selectIndex == 0) {
                        mode = 0x00;
                    } else {
                        mode = 0x01;//恢复出厂设置并且保留地库，暂时模组未实现
                    }
                    mClient.mtcFactoryReset(mode, (mtcCode1, result1) -> {
                        if (mtcCode1 == MtcCode.SUCCESS) {
                            showToast(R.string.notice_success);
                        } else {
                            String errorMsg = getMtcErrorMsg(mtcCode1);
                            showToast(errorMsg);
                        }
                    });
                }).show();
    }

    public void getSn(View v) {
        mClient.mtcDeviceSnGet(0x01, (mtcCode, result) -> {
            if (mtcCode == MtcCode.SUCCESS && !TextUtils.isEmpty(result)) {
                showBasicDialogNoCancel(R.string.get_sn, result);
            } else {
                showToast(getMtcErrorMsg(mtcCode));
            }
        });
    }

    public void getBrightness(View v) {
        mClient.mtcDeviceBrightnessSensorGet((mtcCode, result) -> {

            if (mtcCode == MtcCode.SUCCESS && !TextUtils.isEmpty(result)) {
                int brightness = Integer.parseInt(result);
                showToast("Value:" + brightness);
            } else {
                showToast(getMtcErrorMsg(mtcCode));
            }
        });

    }

    public void getDeviceModel(View v) {
        mClient.mtcDeviceModuleGet((mtcCode, result) -> {
            if (mtcCode == MtcCode.SUCCESS && !TextUtils.isEmpty(result)) {
                showBasicDialogNoCancel(R.string.get_equipment_model, result);
            } else {
                showToast(getMtcErrorMsg(mtcCode));
            }
        });
    }

    public void getFeatures(View v) {
        MaterialDialogUtils.showInputDialog(this, getString(R.string.get_features), "")
                .input("id", "", (@NonNull MaterialDialog dialog, CharSequence input) -> {
                })
                .onPositive((dialog, which) -> {
                    String id = dialog.getInputEditText().getText().toString();
                    MClient.getInstance().mtcAiQueryFeature(id, (mtcCode, result) -> {

                        if (mtcCode == MtcCode.SUCCESS) {
                            if (!TextUtils.isEmpty(result)) {
                                Logger.d("result:" + result);
                                showToast(R.string.have_already_copied);
                                ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                                ClipData mClipData = ClipData.newPlainText("Label", result);
                                cm.setPrimaryClip(mClipData);
                            } else {
                                showToast(R.string.feature_was_not_found);
                            }
                        } else {
                            showToast(getMtcErrorMsg(mtcCode));
                        }
                    });
                }).show();
    }

    public void addFeatures(View v) {
        MaterialDialogUtils.showInputDialog(this, getString(R.string.add_features), getString(R.string.making_sure_have_features))
                .input("id", "", (@NonNull MaterialDialog dialog, CharSequence input) -> {
                })
                .onPositive((dialog, which) -> {
                    ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                    if (cm.hasPrimaryClip()) {
                        ClipData.Item item = cm.getPrimaryClip().getItemAt(0);
                        String features = item.getText().toString();
                        Logger.d("feature: " + features);
                        byte[] featureByte = features.getBytes();
                        String id = dialog.getInputEditText().getText().toString();
                        MClient.getInstance().mtcAiAddFeature(featureByte, id, (mtcCode, result) -> {
                            if (mtcCode == MtcCode.SUCCESS) {
                                showToast(R.string.notice_success);
                            } else {
                                showToast(getMtcErrorMsg(mtcCode));
                            }
                        });
                    } else {
                        showToast(R.string.notice_failure);
                    }

                }).show();
    }

    public void back(View view) {
        finish();
    }


    static class MulitiImgTask extends AsyncTask<Void, Integer, String> {

        WeakReference<SettingActivity> weakReference;
        MaterialDialog progressDialog;

        int mAddUserImageFailedNum = 0;
        int mAddUserImageSuccessdNum = 0;
        int max;
        String userId;
        boolean isCancel = true;

        public MulitiImgTask(SettingActivity settingActivity, int max, String userId) {
            weakReference = new WeakReference<>(settingActivity);
            this.max = max;
            this.userId = userId;
        }

        @Override
        protected void onPreExecute() {
            Logger.d("onPreExecute");
            SettingActivity settingActivity = weakReference.get();
            if (settingActivity == null) {
                return;
            }
            if (progressDialog == null) {
                progressDialog = MaterialDialogUtils.showProgressDialog(settingActivity, settingActivity.getString(R.string.setting_notice_upgrade_process), false, max)
                        .onNegative((dialog, which) -> {
                            isCancel = true;
                        })
                        .build();
            }
            progressDialog.show();
        }

        @Override
        protected String doInBackground(Void... voids) {
            SettingActivity settingActivity = weakReference.get();
            if (settingActivity == null) {
                return null;
            }
            SenseTimeApp senseTimeApp = (SenseTimeApp) settingActivity.getApplication();
            SparseArray<String> selectedImagePaths = senseTimeApp.getSelectedImagePaths();

            StringBuilder addFailedImageNotice = new StringBuilder();
            StringBuilder addSuccessImageNotice = new StringBuilder();
            int progress = 0;
            isCancel = false;
            for (int i = 0; i < selectedImagePaths.size(); i++) {
                if (isCancel) {
                    break;
                }
                String imgPath = selectedImagePaths.valueAt(i);
                String id = "";
                if (max == 1) {
                    id = userId;
                } else if (imgPath != null && imgPath.length() > 0) {
                    id = Util.getFileName(imgPath);
                }
                int ret = settingActivity.applyAddImage(imgPath, id);
                if (ret != 0) {
                    mAddUserImageFailedNum++;
                    Log.e("jglee", "add image ret:" + ret);
                    MtcCode mtcCode = MtcCode.matchRetCode(ret);
                    String reson = settingActivity.getMtcErrorMsg(mtcCode);
                    addFailedImageNotice.append("\n" + mAddUserImageFailedNum + ". id:").append(id + ", ").append(settingActivity.getString(R.string.main_notice_add_user_failure)).append("; ")
                            .append(settingActivity.getString(R.string.notice_reason)).append(": " + reson + ".");
                } else {
                    mAddUserImageSuccessdNum++;
                    addSuccessImageNotice.append("\n" + mAddUserImageSuccessdNum + ". id:").append(id + ", ").append(settingActivity.getString(R.string.main_notice_add_user_success)).append(".");
                }
                progress = progress + 1;
                publishProgress(progress);
            }
            selectedImagePaths.clear();
            senseTimeApp.setSelectedImagePaths(null);
            if (mAddUserImageFailedNum == 0) {
                return "";
            } else {
                return addFailedImageNotice.append("\n\n").append(addSuccessImageNotice).toString();
            }
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            progressDialog.setProgress(values[0]);
        }

        @Override
        protected void onPostExecute(String result) {
            SettingActivity settingActivity = weakReference.get();
            if (settingActivity == null) {
                return;
            }
            if (progressDialog != null && progressDialog.isShowing()) {
                progressDialog.dismiss();
            }
            result = settingActivity.getString(R.string.notice_success) + ": " + mAddUserImageSuccessdNum + "\n"
                    + settingActivity.getString(R.string.notice_failure) + ": " + mAddUserImageFailedNum + "\n"
                    + result;
            MaterialDialogUtils
                    .showBasicDialogNoCancel(settingActivity, settingActivity.getString(R.string.setting_btn_batch_add_user), result)
                    .show();
        }
    }

    private void upgradeFirmwareBtnListener() {
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//            try {
//                Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
//                intent.addCategory(Intent.CATEGORY_OPENABLE);
//                intent.setType("*/*");
//                startActivityForResult(intent, UPGRADE_FIRMWARE);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }


//         如果在你Android设备上用以上方法会报异常： android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.OPEN_DOCUMENT cat=[android.intent
//         .category .OPENABLE] typ=*/* }
//       或者需要自动升级的话， 那么你可以用以下方法写死路径，直接读取

//       If you use the above method on your Android device, an exception will be reported： android.content.ActivityNotFoundException: No Activity found to handle
//       Intent { act=android.intent.action.OPEN_DOCUMENT cat=[android .intent.category .OPENABLE] typ=*/* }
//       Or if you need an automatic upgrade, you can use the following method to write the dead path and read directly

        File file = new File(Environment.getExternalStorageDirectory().getPath()+"/m20_V2.5.6_update_tar.bin");
        Uri uri = null;
        if (file.exists()) {
            uri = Uri.fromFile(file);
        }
        int length = (int) file.length();
        WriteFirmwareTask writeFirmwareTask = new WriteFirmwareTask(this, uri, length);
        writeFirmwareTask.execute();
    }

    @SuppressLint("NewApi")
    @Override
    public synchronized void onActivityResult(int requestCode, int resultCode, Intent resultData) {
        super.onActivityResult(requestCode, resultCode, resultData);
        if (requestCode == UPGRADE_FIRMWARE && resultCode == Activity.RESULT_OK) {
            if (resultData == null) {
                return;
            }
            if (resultData.getData() != null) {
                Uri mUri = resultData.getData();
                assert mUri != null;
                Logger.d("uri: " + mUri.toString());
                MaterialDialogUtils
                        .showBasicDialogNoCancel(this, getString(R.string.setting_btn_upgrade_firmware), FileUtils.getFileName(mUri,
                                getContentResolver()))
                        .onPositive((@NonNull MaterialDialog dialog, @NonNull DialogAction which) -> {


                            WriteFirmwareTask writeFirmwareTask = new WriteFirmwareTask(this, mUri, 0);
                            writeFirmwareTask.execute();
                        })
                        .show();
            }
        } //else if (requestCode == ADD_IMAGE_TO_MTC && resultCode == Activity.RESULT_OK) {
           // imageAdd();
        //}
        else if (requestCode == SELECT_IMG_VERIFY && resultCode == Activity.RESULT_OK) {
            faceRecognizeOneToOne();
        } else if (requestCode == SELECT_IMG_STATIC_RECOGNIZE && resultCode == RESULT_OK) {
            SenseTimeApp senseTimeApp = (SenseTimeApp) getApplication();
            String imgPath = senseTimeApp.getSelectedImagePaths().valueAt(0);
            byte[] data = FileUtils.read(imgPath);
            MaterialDialog progressDialog = MaterialDialogUtils.showIndeterminateProgressDialog(SettingActivity.this, "", false).show();
            MClient.getInstance().mtcAiStaticVerify(0x01, data, (mtcCode, result) -> {
                if (progressDialog != null) {
                    progressDialog.dismiss();
                }

                if (mtcCode != MtcCode.SUCCESS) {
                    result = getMtcErrorMsg(mtcCode);
                } else if (TextUtils.isEmpty(result)) {
                    result = getString(R.string.notice_failure);
                }
                MaterialDialogUtils.showBasicDialogPositive(this, getString(R.string.static_verify), result).show();
            });

        }
    }

    static class WriteFirmwareTask extends AsyncTask<Void, Integer, String> {

        WeakReference<SettingActivity> weakReference;
        MaterialDialog progressDialog;
        Uri mUri;
        int fileSize;
        boolean isCancel = true;

        public WriteFirmwareTask(SettingActivity settingActivity, Uri mUri, int fileSize) {
            weakReference = new WeakReference<>(settingActivity);
            this.mUri = mUri;
            this.fileSize = fileSize;
        }

        @Override
        protected void onPreExecute() {
            SettingActivity settingActivity = weakReference.get();
//            if (fileSize == 0) {
//                fileSize = FileUtils.getFileSize(mUri, settingActivity.getContentResolver(), settingActivity);
//            }
            if (progressDialog == null && settingActivity != null) {
                progressDialog = MaterialDialogUtils
                        .showProgressDialog(settingActivity, settingActivity.getString(R.string.setting_btn_upgrade_firmware), true, fileSize)
                        .onNegative((dialog, which) -> {
                            isCancel = true;
                        })
                        .build();
            }
            progressDialog.show();
        }

        @Override
        protected String doInBackground(Void... voids) {
            SettingActivity settingActivity = weakReference.get();
            if (settingActivity == null) {
                return null;
            }

            FileDescriptor fileDescriptor;
            InputStream inputStream = null;
            String md5 = null;
            try {
                ParcelFileDescriptor parcelFileDescriptor = settingActivity.getContentResolver().openFileDescriptor(mUri, "r");
                if (parcelFileDescriptor != null) {
                    fileDescriptor = parcelFileDescriptor.getFileDescriptor();
                    md5 = FileUtils.getFileMD5(fileDescriptor);
                    Logger.d("The File MD5 is " + md5);
                } else {
                    return settingActivity.getString(R.string.file_can_not_open);
                }
                inputStream = settingActivity.getContentResolver().openInputStream(mUri);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            if (fileSize <= 0) {
                return settingActivity.getString(R.string.file_size_zero);
            }
            try {
                int position = 0;
                isCancel = false;
                while (position <= fileSize) {
                    if (isCancel) {
                        break;
                    }

                    int leftOver = fileSize - position;
                    if (leftOver <= 0)
                        break;
                    int needReadLength = MClient.MTC_UPGRADE_SEGMENT_LENGTH <= leftOver ? MClient.MTC_UPGRADE_SEGMENT_LENGTH : leftOver;

                    byte[] data = new byte[needReadLength];
                    int readLengthRet;
                    if (inputStream != null) {
                        readLengthRet = inputStream.read(data, 0, needReadLength);
                    } else {
                        return settingActivity.getString(R.string.inputStream_is_null);
                    }
                    if (readLengthRet <= 0) {
                        Log.e("jglee", "The firmware file read done.");
                        break;
                    }
                    if (data == null || readLengthRet == 0 || readLengthRet > MClient.MTC_UPGRADE_SEGMENT_LENGTH) {
                        return settingActivity.getString(R.string.check_firmware);
                    }
//                    Logger.d("readLengthRet:" + readLengthRet + ",  needReadLength:" + needReadLength);
                    Log.d("Upgrade", "Upgrade START " + "readLengthRet:" + readLengthRet + ",  needReadLength:" + needReadLength);
                    int retry = 3;
                    while (--retry>0) {
                        int mtcUpgradeUpload = MClient.getInstance().mtcSystemUploadUpgradePackage(position, data, readLengthRet);
                        Log.d("Upgrade", "Upgrade return " + mtcUpgradeUpload);
                        if (mtcUpgradeUpload != 0) {
//                        Log.e(TAG, "Upload firmware file failure.  mtcSystemUploadUpgradePackage: " + mtcUpgradeUpload);
                            if (mtcUpgradeUpload == -2) {
                                //MainActivity.mIOInterface.Reboot(0);
                                return settingActivity.getString(R.string.check_firmware);

                            }else if (mtcUpgradeUpload == -13){
                                Log.d("Upgrade", "Upgrade TIMEOUT");
                                //MainActivity.mIOInterface.Reboot(0);
                                //return settingActivity.getString(R.string.time_out);
                                continue;
                            }
                            //MainActivity.mIOInterface.Reboot(0);
                            return settingActivity.getString(R.string.setting_notice_upgrade_failure_upload);
                        }
                        else
                            break;
                    }

                    Log.d("Upgrade", "Upgrade Size " + "process: " + String.format("%.2f", (double) position / (double) fileSize * 100) + "%");
                    position += readLengthRet;
                    publishProgress(position);
//                    Logger.d("process: " + String.format("%.2f", (double) position / (double) fileSize * 100) + "%");
                }
                if (inputStream != null)
                    inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (isCancel) {
                return settingActivity.getString(R.string.dialog_btn_cancelled);
            }
            StringBuffer sb = new StringBuffer(); // 새로운 객체로 교체
            if (MClient.getInstance().mtcSystemApplyUpgradePackage(md5, sb) != 0) {
                //MainActivity.mIOInterface.Reboot(0);
                return settingActivity.getString(R.string.notice_failure);
            } else {
                //MainActivity.mIOInterface.Reboot(0);
                return settingActivity.getString(R.string.setting_notice_after_reboot);
            }
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            progressDialog.setProgress(values[0]);
        }

        @Override
        protected void onPostExecute(String result) {
            SettingActivity settingActivity = weakReference.get();
            if (settingActivity == null) {
                return;
            }
            if (progressDialog != null && progressDialog.isShowing()) {
                progressDialog.dismiss();
            }
            MaterialDialogUtils.showBasicDialogNoCancel(settingActivity, "", result)
                    .onPositive((dialog, which) -> {
                        if (!TextUtils.isEmpty(result) && settingActivity.getString(R.string.setting_notice_after_reboot).equals(result)) {
                            SenseTimeApp senseTimeApp = (SenseTimeApp) settingActivity.getApplication();
                            senseTimeApp.exitApp();
                        }
                    })
                    .show();
        }
    }
}
