package xn.hxp.ui.start;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;

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

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.ThreadUtils;
import com.hjq.http.EasyHttp;
import com.hjq.http.model.ResponseClass;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;

import java.util.concurrent.ThreadLocalRandom;

import okhttp3.HttpUrl;
import xn.hxp.databinding.ActivityStartBinding;
import xn.hxp.http.HttpData;
import xn.hxp.http.api.GetBaseConfigApi;
import xn.hxp.http.api.GetReportApi;
import xn.hxp.room.bean.BaseConfig;
import xn.hxp.room.bean.DeviceInfo;
import xn.hxp.room.bean.LabInfo;
import xn.hxp.room.tool.BaseConfigTool;
import xn.hxp.room.tool.DeviceInfoTool;
import xn.hxp.room.tool.LabInfoTool;
import xn.hxp.ui.main.MainActivity;
import xn.hxp.util.Tool;

public class StartActivity extends AppCompatActivity {
    private ActivityStartBinding binding;
    private DeviceInfo deviceInfo;
    private CountDownTimer requestPermissionCdTimer;
    private LabInfo labInfo;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityStartBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        deviceInfo = DeviceInfoTool.INSTANCE.getDeviceInfo();
        // ip
        String ip = deviceInfo.getIp();
        binding.ip.setText(TextUtils.isEmpty(ip) ? "" : ip);
        // 版本
        binding.version.setText(AppUtils.getAppVersionName());

        requestPermissionCdTimer = new CountDownTimer(1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {

            }

            @Override
            public void onFinish() {
                requestPermission();
            }
        };
        requestPermissionCdTimer.start();
    }

    private void requestPermission() {
        if (!XXPermissions.isGrantedPermissions(this, Permission.READ_EXTERNAL_STORAGE)
                || !XXPermissions.isGrantedPermissions(this, Permission.WRITE_EXTERNAL_STORAGE)
                || !XXPermissions.isGrantedPermissions(this, Permission.READ_PHONE_STATE)
                || !XXPermissions.isGrantedPermissions(this, Permission.RECORD_AUDIO)
                || !XXPermissions.isGrantedPermissions(this, Permission.SYSTEM_ALERT_WINDOW)
        ) {
            Tool.INSTANCE.cmd("pm grant " + AppUtils.getAppPackageName() + " android.permission.READ_EXTERNAL_STORAGE");
            Tool.INSTANCE.cmd("pm grant " + AppUtils.getAppPackageName() + " android.permission.WRITE_EXTERNAL_STORAGE");
            Tool.INSTANCE.cmd("pm grant " + AppUtils.getAppPackageName() + " android.permission.READ_PHONE_STATE");
            Tool.INSTANCE.cmd("pm grant " + AppUtils.getAppPackageName() + " android.permission.RECORD_AUDIO");
            Tool.INSTANCE.cmd("pm grant " + AppUtils.getAppPackageName() + " android.permission.SYSTEM_ALERT_WINDOW");
            requestPermissionCdTimer.start();
        } else {
            requestPermissionCdTimer.cancel();
            initView();
        }
    }

    private void initView() {
        binding.logo.setOnLongClickListener(v -> {
            ActivityUtils.startActivity(SettingActivity.class);
            finish();
            return true;
        });

        ThreadUtils.executeByCached(new ThreadUtils.SimpleTask<Object>() {
            @Override
            public Object doInBackground() throws Throwable {
                // 检查网络
                isAvailableByPing();
                ThreadUtils.runOnUiThread(() -> binding.hint.setText("获取实验室信息"));
                // 获取实验室信息
                getLabInfo();
                ThreadUtils.runOnUiThread(() -> binding.hint.setText("获取基础信息"));
                // 获取基础信息
                getLabConfig();
                ThreadUtils.runOnUiThread(() -> binding.hint.setText("初始化已完成"));
                return null;
            }

            @Override
            public void onSuccess(Object result) {
                ActivityUtils.startActivity(MainActivity.class);
                finish();
            }
        });
    }

    @WorkerThread
    private void getLabConfig() throws Throwable {
        try {
            HttpData<BaseConfig> data = EasyHttp.get(StartActivity.this).api(new GetBaseConfigApi(labInfo.getSubjectId())).execute(new ResponseClass<>() {
            });

            if (data.isRequestSuccess()) {
                BaseConfig baseConfig = data.getData();
                if (null != baseConfig) {
                    BaseConfigTool.INSTANCE.insert(baseConfig);
                    return;
                }
            }
        } catch (Exception e) {
            LogUtils.e(e.getMessage());
        }
        Thread.sleep(1000L * ThreadLocalRandom.current().nextInt(10, 20));
        getLabConfig();
    }

    @WorkerThread
    private void getLabInfo() throws Throwable {
        try {
            HttpData<GetReportApi.Bean> data = EasyHttp.get(StartActivity.this).api(new GetReportApi()).execute(new ResponseClass<>() {
            });
            if (data.isRequestSuccess()) {
                GetReportApi.Bean bean = data.getData();
                if (null != bean) {
                    labInfo = bean.getLabInfo();
                    if (null != labInfo) {
                        LabInfoTool.INSTANCE.insert(labInfo);
                        return;
                    }
                }
            }
        } catch (Exception e) {
            LogUtils.e(e.getMessage());
        }
        Thread.sleep(1000L * ThreadLocalRandom.current().nextInt(10, 20));
        getLabInfo();
    }

    @WorkerThread
    private void isAvailableByPing() throws InterruptedException {
        if (!NetworkUtils.isAvailableByPing(HttpUrl.get(deviceInfo.getBaseUrl()).host())) {
            Thread.sleep(1000L * ThreadLocalRandom.current().nextInt(10, 20));
            isAvailableByPing();
        }
    }
}
