package com.geek.demo.activity;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.geek.demo.BuildConfig;
import com.geek.demo.R;
import com.geek.demo.model.LeaveShopData;
import com.geek.demo.model.ResidentShopData;
import com.geek.demo.model.SceneData;
import com.geek.demo.view.SceneCard;
import com.google.gson.Gson;
import com.sharedream.geek.sdk.GeekCallback;
import com.sharedream.geek.sdk.GeekSdk;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private Button btnFeedback;
    private Button btnRegister;
    private Button btnRelease;
    private Button btnStart;
    private Button btnStop;
    private List<SceneData> sceneList = new ArrayList<>(); // 存储小场景
    private List<SceneData> parentSceneList = new ArrayList<>(); // 存储大场景
    private SceneCard sceneCard;
    private TextView tvVersion;
    private long exitTime;
    private boolean isCloseApp;
    private Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = getApplicationContext();
        initView();
        checkAndRequestPermissions();
    }

    private void checkAndRequestPermissions() {
        List<String> permissionList = checkPermissions();
        if (permissionList.size() == 0) {
            initSdk();
            return;
        }
        showPermissionDialog(permissionList);
    }

    private void showPermissionDialog(List<String> permissionList) {
        String[] requestPermissions = new String[permissionList.size()];
        permissionList.toArray(requestPermissions);
        ActivityCompat.requestPermissions(MainActivity.this, requestPermissions, 8888);
    }

    private ArrayList<String> checkPermissions() {
        ArrayList<String> requestPermissionList = new ArrayList<>();

        //READ_PHONE_STATE不是SDK必须权限，此处仅仅用于APP业务
        boolean phoneStateCheckResult = ContextCompat.checkSelfPermission(getApplicationContext(),
                Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED;
        if (!phoneStateCheckResult) {
            requestPermissionList.add(Manifest.permission.READ_PHONE_STATE);
        }

        boolean locationCheckResult = ContextCompat.checkSelfPermission(getApplicationContext(),
                Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;
        if (!locationCheckResult) {
            requestPermissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
        }

        boolean wifiCheckResult = ContextCompat.checkSelfPermission(getApplicationContext(),
                Manifest.permission.CHANGE_WIFI_STATE) == PackageManager.PERMISSION_GRANTED;
        if (!wifiCheckResult) {
            requestPermissionList.add(Manifest.permission.CHANGE_WIFI_STATE);
        }

        boolean bluetoothCheckResult = ContextCompat.checkSelfPermission(getApplicationContext(),
                Manifest.permission.BLUETOOTH_ADMIN) == PackageManager.PERMISSION_GRANTED;
        if (!bluetoothCheckResult) {
            requestPermissionList.add(Manifest.permission.BLUETOOTH_ADMIN);
        }

        return requestPermissionList;
    }

    private void initView() {
        btnFeedback = findViewById(R.id.btn_feedback);
        btnRegister = findViewById(R.id.btn_register);
        btnRelease = findViewById(R.id.btn_release);
        btnStart = findViewById(R.id.btn_start);
        btnStop = findViewById(R.id.btn_stop);
        sceneCard = findViewById(R.id.scene_card);
        tvVersion = findViewById(R.id.tv_version);
        btnRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initSdk();
            }
        });

        btnRelease.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                GeekSdk.release();
                btnRegister.setText("注册");
            }
        });

        btnStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                GeekSdk.startSceneRecognization();
            }
        });

        btnStop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                GeekSdk.stopSceneRecognization();
            }
        });

        btnFeedback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                GeekSdk.uploadLog();
            }
        });

        tvVersion.setText(BuildConfig.VERSION_NAME);
    }

    private void initSdk() {
        Log.i(TAG, "初始化");
        context = getApplicationContext();//注意：Application 的 Context
        JSONObject initParam = new JSONObject();
        try {
            initParam.put(GeekSdk.INIT_PARAM_CONTEXT, context);//必要参数
            initParam.put(GeekSdk.INIT_PARAM_OAID, "123456789");//必要参数，如果没有oaid可以自行定义id，需保证每个用户唯一性
            initParam.put(GeekSdk.INIT_PARAM_ACCESS_KEY, "U5Gq8ZFHulgWWitFAgSjYrHoNKTSNgCD");//必要参数，在及刻开放平台申请自己的ak
            GeekSdk.init(initParam, new GeekCallback() {
                @Override
                public void onCallback(final int event, final JSONObject jsonData) {//jsonData内部字段注意判空
                    Log.i(TAG, "event：" + event + ", jsonData：" + jsonData.toString());
                    int result = jsonData.optInt("result");
                    switch (event) {
                        //todo 初始化SDK响应事件 开发者自行实现此case编码
                        case GeekCallback.EVENT_SDK_INIT:
                            if (result == GeekCallback.INIT_RESULT_SUCCESS || result == GeekCallback.INIT_RESULT_REGISTERED) {
                                GeekSdk.startSceneRecognization();
                                showInfo(btnRegister, "注册成功，开始场景识别");
                            } else {
                                showInfo(btnRegister, "注册失败，错误码：" + result);
                            }
                            break;

                        //todo 进入场景 开发者自行实现此case编码
                        case GeekCallback.EVENT_SDK_RESIDENT_SHOP:
                            String residentShopDataJson = jsonData.toString().replaceAll("class", "clazz");
                            ResidentShopData residentShopData = new Gson().fromJson(residentShopDataJson, ResidentShopData.class);
                            if (result == GeekCallback.RESULT_SUCCESS) {
                                handleResidentShop(residentShopData.data);
                            }
                            break;

                        //todo 离开场景 开发者自行实现此case编码
                        case GeekCallback.EVENT_SDK_LEAVE_SHOP:
                            LeaveShopData leaveShopData = new Gson().fromJson(jsonData.toString(), LeaveShopData.class);
                            if (result == GeekCallback.RESULT_SUCCESS) {
                                handleLeaveShop(leaveShopData.data);
                            }
                            break;

                        //todo 上传日志 开发者自行实现此case编码
                        case GeekCallback.EVENT_SDK_UPLOAD_LOG:
                            if (result == GeekCallback.RESULT_SUCCESS) {
                                showToast("提交成功");
                            } else {
                                showToast("提交失败，" + result);
                            }
                            break;
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void showInfo(final Button bt, final String msg){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                bt.setText(msg);
            }
        });
    }

    private void showToast(final String msg){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 离店处理
     *
     * @param data
     */
    private void handleLeaveShop(List<LeaveShopData.LeaveShop> data) {
        if (data == null || data.isEmpty()) {
            sceneList.clear();
            parentSceneList.clear();
            sceneCard.notifySceneCard(null, null);
        } else {
            for (LeaveShopData.LeaveShop leaveShop : data) {
                SceneData sceneData = new SceneData();
                sceneData.poiId = leaveShop.poiId;
                sceneList.remove(sceneData);
                parentSceneList.remove(sceneData);
            }
            updateSceneCard();
        }
    }

    /**
     * 进店处理
     *
     * @param data
     */
    private void handleResidentShop(List<SceneData> data) {
        if (data != null && !data.isEmpty()) {
            for (SceneData sceneData : data) {
                if (sceneData.clazz == 1) {
                    if (!sceneList.contains(sceneData)) {
                        sceneList.add(0, sceneData);
                    } else {
                        sceneList.remove(sceneData);
                        sceneList.add(0, sceneData);
                    }
                }
                if (sceneData.clazz >= 2) {
                    if (!parentSceneList.contains(sceneData)) {
                        parentSceneList.add(0, sceneData);
                    } else {
                        parentSceneList.remove(sceneData);
                        parentSceneList.add(0, sceneData);
                    }
                }
            }
            updateSceneCard();
        }
    }

    /**
     * 更新场景卡界面
     */
    private void updateSceneCard() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (sceneList.isEmpty() && parentSceneList.isEmpty()) {
                    sceneCard.notifySceneCard(null, null);
                } else {
                    if (!sceneList.isEmpty()) {
                        if (!parentSceneList.isEmpty()) {
                            sceneCard.notifySceneCard(sceneList.get(0), parentSceneList.get(0));
                        } else {
                            if (sceneList.size() >= 2) {
                                sceneCard.notifySceneCard(sceneList.get(0), sceneList.get(1));
                            } else {
                                sceneCard.notifySceneCard(sceneList.get(0), null);
                            }
                        }
                    } else {
                        if (parentSceneList.size() >= 2) {
                            sceneCard.notifySceneCard(parentSceneList.get(0), parentSceneList.get(1));
                        } else {
                            sceneCard.notifySceneCard(parentSceneList.get(0), null);
                        }
                    }
                }
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 8888) {
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
                    Toast.makeText(MainActivity.this,"授权失败：" + permissions[i], Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    //对返回键进行监听
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            exit();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    //双击返回键关闭app
    public void exit() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            Toast.makeText(context, "再按一次退出" + getString(R.string.app_name), Toast.LENGTH_SHORT).show();
            exitTime = System.currentTimeMillis();
        } else {
            isCloseApp = true;
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        GeekSdk.release();
        if (isCloseApp) {
            android.os.Process.killProcess(android.os.Process.myPid());
        }
    }

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


