package com.hh.arome;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.app.ProgressDialog;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alipay.arome.aromecli.AromeInit;
import com.alipay.arome.aromecli.AromeInitOptions;
import com.alipay.arome.aromecli.AromeServiceInvoker;
import com.alipay.arome.aromecli.AromeServiceTask;
import com.alipay.arome.aromecli.requst.AromeActivateRequest;
import com.alipay.arome.aromecli.requst.AromeLaunchAppRequest;
import com.alipay.arome.aromecli.requst.AromeSendEventRequest;
import com.alipay.arome.aromecli.response.AromeActivateResponse;
import com.alipay.arome.aromecli.response.AromeLaunchAppResponse;
import com.alipay.arome.aromecli.response.AromeResponse;
import com.hh.arome.http.JsonResponse;
import com.hh.arome.http.params.AmpeJsonParams;
import com.hh.arome.http.response.AmpeJsonResponse;
import com.hh.arome.services.IDReaderService;
import com.hh.arome.services.QrcodeScannerService;
import com.hh.arome.util.BarcodeScannerHelper;
import com.hh.arome.util.Utils;

import org.json.JSONException;
import org.xutils.common.Callback;
import org.xutils.x;

import java.util.concurrent.atomic.AtomicInteger;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();
    public static final int REQUEST_CODE_Accessibility = 19999;

    private Handler mMainHandler = new Handler(Looper.getMainLooper());
    private Handler mWorkerThread = null;
    private ProgressDialog mProgressDialog;
    private AtomicInteger mDialogToken = new AtomicInteger(0);

    // 设备的配置参数
    private AmpeJsonResponse ampeJson = null;

    /**
     * ServiceConnection代表与服务的连接，它只有两个方法，
     * onServiceConnected和onServiceDisconnected，
     * 前者是在操作者在连接一个服务成功时被调用，而后者是在服务崩溃或被杀死导致的连接中断时被调用
     */
    private ServiceConnection conn;
    private IDReaderService mService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        init();
        if(initQrcodeScannerData(true)) {
            initAmpeData();
        }
//        initBarcodeScanner();
//        initService();
    }

    private void init() {
        HandlerThread workerHandlerThread = new HandlerThread("arome_worker");
        workerHandlerThread.start();
        mWorkerThread = new Handler(workerHandlerThread.getLooper());
    }

    private boolean initQrcodeScannerData(boolean auto) {
        if(!QrcodeScannerService.isAccessibilitySettingsOn(this)) {
            if(auto) {
                Toast.makeText(x.app(), "请开启该应用的无障碍辅助服务!", Toast.LENGTH_LONG).show();
                startActivityForResult(new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS), REQUEST_CODE_Accessibility);
            }
            return false;
        }
        return true;
    }

    private void initAmpeData() {
        final int token = showLoading("正在激活...");
        AmpeJsonParams ampeJsonParams = new AmpeJsonParams(Utils.getIotVersion());
        ampeJsonParams.send(new Callback.CommonCallback<JsonResponse<AmpeJsonResponse>>() {
            @Override
            public void onSuccess(JsonResponse<AmpeJsonResponse> result) {
                System.out.println("onSuccess-->" + result);
//                Toast.makeText(x.app(), result.toString(), Toast.LENGTH_LONG).show();
                ampeJson = result.getData();
                if(ampeJson == null || TextUtils.isEmpty(ampeJson.getAPP_ID())) {
                    Toast.makeText(x.app(), "获取到的配置参数为空!", Toast.LENGTH_LONG).show();
                    return;
                }
                initAmpe();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                System.out.println("onError-->" + isOnCallback);
//                Toast.makeText(x.app(), ex.getMessage(), Toast.LENGTH_LONG).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                System.out.println("onCancelled-->");
//                Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFinished() {
                System.out.println("onFinished-->");
                hideLoading(token);
            }
        });
    }

    // 初始化扫码
    private void initBarcodeScanner() {
        BarcodeScannerHelper.getInstance().setScanSuccessListener(new BarcodeScannerHelper.OnScanSuccessListener() {
            @Override
            public void onScanSuccess(String barcode) {
                Toast.makeText(MainActivity.this, "扫码内容：" + barcode, Toast.LENGTH_LONG).show();
                System.out.println(TAG + "-" + barcode);
            }
        });
    }

    private void initService() {
        conn = new ServiceConnection() {
            /**
             * 与服务器端交互的接口方法 绑定服务的时候被回调，在这个方法获取绑定Service传递过来的IBinder对象，
             * 通过这个IBinder对象，实现宿主和Service的交互。
             */
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                Log.d(TAG, "绑定成功调用：onServiceConnected");
                IDReaderService.LocalBinder binder = (IDReaderService.LocalBinder) service;
                mService = binder.getService();
            }
            /**
             * 当取消绑定的时候被回调。但正常情况下是不被调用的，它的调用时机是当Service服务被意外销毁时，
             * 例如内存的资源不足时这个方法才被自动调用。
             */
            @Override
            public void onServiceDisconnected(ComponentName name) {
                mService = null;
            }
        };
        Intent intent = new Intent(this, IDReaderService.class);
        bindService(intent, conn, Service.BIND_AUTO_CREATE);
    }

    private void initAmpe() {
        // 设备信息配置
        Bundle deviceConfig = new Bundle();
        deviceConfig.putString("packageName", "com.hh.arome");
        Bundle themeConfig = new Bundle();
        themeConfig.putBoolean("hideStatusBar", true);
        themeConfig.putBoolean("hideNavigationBar", true);
        themeConfig.putBoolean("hideOptionMenu", true);

        AromeInit.init(new AromeInitOptions.Builder()
                .loginMode(0)
                .hardwareType(0)
                .hardwareName("杭州航汇数字YX08政务刷脸自助机")
                .deviceConfig(deviceConfig)
                .themeConfig(themeConfig)
                .build(), new AromeInit.Callback() {
            @Override
            public void postInit(boolean success, int errorCode, String errorMsg) {
                if(success) {
                    activateDevice(null);
                } else {
                    Toast.makeText(MainActivity.this, "失败:" + errorMsg, Toast.LENGTH_LONG).show();
                }
            }
            @Override
            public void serverDied() {

            }
        });
    }

    public void activateDevice(View view) {
        final int token = showLoading("正在加载...");
        mWorkerThread.post(new Runnable() {
            @Override
            public void run() {
                AromeActivateRequest request = new AromeActivateRequest();
                request.hostAppId = ampeJson.getHOST_APP_ID();
                request.deviceId = ampeJson.getDEVICE_ID();
                request.signature = ampeJson.getSignature();
                try{
                    request.productId = Integer.parseInt(ampeJson.getPRODUCT_ID());
                } catch (Exception e) {
                    throw new NullPointerException("productId不能为空");
                }
                AromeServiceInvoker.invoke(request, new AromeServiceTask.Callback<AromeActivateResponse>() {
                    @Override
                    public void onCallback(final AromeActivateResponse response) {
                        mMainHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                if(response.success) {
                                    launchApp();
                                } else {
                                    Toast.makeText(MainActivity.this, "激活失败:" + response.message, Toast.LENGTH_LONG).show();
                                }
                            }
                        });
                    }
                });
                hideLoading(token);
            }
        });
    }

    private void launchApp() {
        final int token = showLoading("正在启动...");
        mWorkerThread.post(new Runnable() {
            @Override
            public void run() {
                AromeLaunchAppRequest request = new AromeLaunchAppRequest();
                // 指定启动 appId
                request.appId = ampeJson.getAPP_ID();
                request.closeAllApp = true;

                // 指定启动的显示类型 showType
                // 指定启动时小程序主体的显示宽度 launchWidth
                Bundle themeConfig = new Bundle();
                request.themeConfig = themeConfig;

                AromeServiceInvoker.invoke(request, new AromeServiceTask.Callback<AromeLaunchAppResponse>() {
                    @Override
                    public void onCallback(final AromeLaunchAppResponse response) {
                        mMainHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                if(response.success) {
//                                    Toast.makeText(MainActivity.this, "小程序启动成功:", Toast.LENGTH_LONG).show();
                                } else {
                                    Toast.makeText(MainActivity.this, "启动失败:" + response.message, Toast.LENGTH_LONG).show();
                                }
                            }
                        });
                    }
                });
                hideLoading(token);
            }
        });
    }

    // 用户手动离开当前activity，会调用该方法，比如用户主动切换任务，短按home进入桌面等。系统自动切换activity不会调用此方法，如来电，灭屏等。
    @Override
    protected void onUserLeaveHint() {
        System.out.println("---->onUserLeaveHint---->");
        super.onUserLeaveHint();
    }

    // activity在分发各种事件的时候会调用该方法，注意：启动另一个activity,onUserInteraction()会被调用两次，一次是activity捕获到事件，另一次是调用Activity#onUserLeaveHint()之前会调用Activity#onUserInteraction()。
    @Override
    public void onUserInteraction() {
        System.out.println("---->onUserInteraction---->");
        super.onUserInteraction();
    }

    private int showLoading(final String text) {
        Utils.runOnMain(new Runnable() {
            @Override
            public void run() {
                if (mProgressDialog != null) {
                    mProgressDialog.dismiss();
                    mProgressDialog = null;
                }
                mProgressDialog = ProgressDialog.show(MainActivity.this, "", text, true, true);
            }
        });
        return mDialogToken.addAndGet(1);
    }

    private void hideLoading(final int token) {
        Utils.runOnMain(new Runnable() {
            @Override
            public void run() {
                // 防止dismiss串后续dialog
                if (token != mDialogToken.get()) {
                    return;
                }
                if (mProgressDialog != null) {
                    mProgressDialog.dismiss();
                    mProgressDialog = null;
                }
            }
        }, 500);
    }

//    @Override
//    public boolean dispatchKeyEvent(KeyEvent event) {
//        if(BarcodeScannerHelper.getInstance().dispatchKeyEvent(event)) {
//            return true;
//        }
//        return super.dispatchKeyEvent(event);
//    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == REQUEST_CODE_Accessibility) {
            // 检查权限是否已经被授权
            boolean success = initQrcodeScannerData(false);
            if(!success) {
                Toast.makeText(x.app(), "未无障碍辅助服务，将不能使用扫码服务!", Toast.LENGTH_LONG).show();
            }
            initAmpeData();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onDestroy() {
        if(BarcodeScannerHelper.getInstance() != null) {
            BarcodeScannerHelper.getInstance().removeScanSuccessListener();
        }
        // 解除绑定
        if(mService != null) {
            mService = null;
            unbindService(conn);
        }
        super.onDestroy();
    }
}