package ezviz.ezopensdkcommon.configwifi;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.Postcard;
import com.alibaba.android.arouter.facade.callback.NavCallback;
import com.alibaba.android.arouter.launcher.ARouter;
import com.ezviz.sdk.configwifi.EZConfigWifiErrorEnum;

import ezviz.ezopensdkcommon.R;
import ezviz.ezopensdkcommon.common.CircularProgressView;
import ezviz.ezopensdkcommon.common.IntentConstants;
import ezviz.ezopensdkcommon.common.LogUtil;
import ezviz.ezopensdkcommon.common.RootActivity;
import ezviz.ezopensdkcommon.common.RouteNavigator;
import ezviz.ezopensdkcommon.common.TitleBar;

public class ConfigWifiExecutingActivity extends RootActivity implements ConfigWifiExecutingActivityPresenter.Callback {

    private final static String TAG = ConfigWifiExecutingActivity.class.getSimpleName();

    private ConfigWifiExecutingActivityPresenter mPresenter;

    // UI 控件
    private CircularProgressView progressRing;
    private TextView tvPercent;
    private TextView tvHint;
    private View stepsContainer;
    private View stepConnected;
    private View stepRegistering;
    private ProgressBar progressRegistering;
    private ImageView checkRegistered;
    private TextView tvRegistering;

    // 虚假进度相关
    private Handler mHandler = new Handler();
    private int mFakeProgress = 0;
    private Runnable mProgressRunnable;

    public static void launch(Context context, Intent intent) {
        Intent newIntent = new Intent(context, ConfigWifiExecutingActivity.class);
        newIntent.putExtras(intent);
        newIntent.putExtra(IntentConstants.USE_MANUAL_AP_CONFIG, true);
        context.startActivity(newIntent);
    }

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

        mPresenter =
                ConfigWifiExecutingActivityPresenter.getPresenter(getIntent().getStringExtra(IntentConstants.SELECTED_PRESENTER_TYPE));
        if (mPresenter == null) {
            LogUtil.e(TAG, "failed to init!");
            return;
        }
        initTitleBar();
        initUI();
        getWindow().getDecorView().post(new Runnable() {
            @Override
            public void run() {
                startConfig();
                startFakeProgress();
            }
        });
    }

    @Override
    protected void onStop() {
        super.onStop();
        // AP配网时系统弹出网络确认对话框会触发 onStop，此时不能退出配网
        // 仅当 Activity 被完全销毁时才停止（通过 onDestroy 或用户主动返回）
    }

    @Override
    protected void onDestroy() {
        stopFakeProgress();
        stopConfig();
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        exitPage();
    }

    private void exitPage() {
        stopFakeProgress();
        stopConfig();
        finish();
    }

    private void initTitleBar() {
        TitleBar titleBar = findViewById(R.id.title_bar);
        titleBar.setTitle(R.string.configuring_title);
        titleBar.addBackButton(v -> onBackPressed());
    }

    private void initUI() {
        progressRing = findViewById(R.id.progressRing);
        tvPercent = findViewById(R.id.tvPercent);
        tvHint = findViewById(R.id.tvHint);
        stepsContainer = findViewById(R.id.stepsContainer);
        stepConnected = findViewById(R.id.stepConnected);
        stepRegistering = findViewById(R.id.stepRegistering);
        progressRegistering = findViewById(R.id.progressRegistering);
        checkRegistered = findViewById(R.id.checkRegistered);
        tvRegistering = findViewById(R.id.tvRegistering);
    }

    /**
     * 启动虚假进度，每秒增加1%
     */
    private void startFakeProgress() {
        mFakeProgress = 0;
        mProgressRunnable = new Runnable() {
            @Override
            public void run() {
                if (mFakeProgress < 99) {
                    mFakeProgress++;
                    progressRing.setProgress(mFakeProgress);
                    tvPercent.setText(String.valueOf(mFakeProgress));
                    mHandler.postDelayed(this, 1000);
                }
            }
        };
        mHandler.postDelayed(mProgressRunnable, 1000);
    }

    private void stopFakeProgress() {
        if (mProgressRunnable != null) {
            mHandler.removeCallbacks(mProgressRunnable);
        }
    }

    /**
     * 回调：成功连接设备热点
     * 隐藏"正在配置设备网络"提示，显示步骤列表
     */
    @Override
    public void onConnectedToWifi() {
        LogUtil.i(TAG, "onConnectedToWifi");
        runOnUiThread(() -> {
            // 隐藏提示文字
            tvHint.setVisibility(View.GONE);
            // 显示步骤容器
            stepsContainer.setVisibility(View.VISIBLE);
            // 步骤1：成功连接网络（蓝色勾）
            stepConnected.setVisibility(View.VISIBLE);
            // 步骤2：正在注册到平台（进度圈）
            stepRegistering.setVisibility(View.VISIBLE);
            progressRegistering.setVisibility(View.VISIBLE);
            checkRegistered.setVisibility(View.GONE);
            tvRegistering.setText(R.string.configuring_step_registering);
            tvRegistering.setTextColor(0x80000000);
        });
    }

    /**
     * 回调：设备成功注册到平台
     * 更新步骤2为"成功注册到平台"+蓝色勾，跳转设备添加页面
     */
    @Override
    public void onConnectedToPlatform() {
        LogUtil.i(TAG, "onConnectedToPlatform");
        runOnUiThread(() -> {
            // 停止虚假进度，显示100%
            stopFakeProgress();
            progressRing.setProgress(100);
            tvPercent.setText("100");

            // 步骤2：成功注册到平台（蓝色勾）
            progressRegistering.setVisibility(View.GONE);
            checkRegistered.setVisibility(View.VISIBLE);
            tvRegistering.setText(R.string.configuring_step_registered);
            tvRegistering.setTextColor(0xE0000000);
        });

        // 延迟跳转设备添加页面
        mHandler.postDelayed(() -> {
            boolean bindRequired = true;
            if (getIntent().getStringExtra(IntentConstants.SELECTED_PRESENTER_TYPE).equals(ConfigWifiTypeConstants.FULL_SDK_APHTTP)) {
                bindRequired = false;
            }
            ARouter.getInstance().build(RouteNavigator.ADD_DEVICE_PAGE)
                    .withString(IntentConstants.DEVICE_SERIAL, getIntent().getStringExtra(IntentConstants.DEVICE_SERIAL))
                    .withString(IntentConstants.DEVICE_VERIFY_CODE, getIntent().getStringExtra(IntentConstants.DEVICE_VERIFY_CODE))
                    .withBoolean(IntentConstants.DEVICE_BIND_REQUIRED, bindRequired)
                    .withFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK)
                    .navigation(this, new NavCallback() {
                        @Override
                        public void onArrival(Postcard postcard) {
                            finish();
                        }

                        @Override
                        public void onLost(Postcard postcard) {
                            // do nothing
                        }
                    });
        }, 1000);
    }

    @Override
    public void onConfigInfo(int info) {

    }

    @Override
    public void onConfigError(int code, String msg) {
        String errorInfo = "error code: " + code + ", msg: " + msg;
        LogUtil.e(TAG, errorInfo);
        // 用户拒绝连接设备热点则认为配网失败
        if (code == EZConfigWifiErrorEnum.USER_REFUSED_CONNECTION_REQUEST.code) {
            failedToConfig();
        }
    }

    @Override
    public void onTimeout() {
        failedToConfig();
    }

    private void failedToConfig() {
        stopConfig();
        stopFakeProgress();
        switch (mPresenter.getType()) {
            case ConfigWifiTypeConstants.CONFIG_WIFI_SDK_AP:
            case ConfigWifiTypeConstants.FULL_SDK_AP:
            case ConfigWifiTypeConstants.FULL_SDK_APHTTP:
                ManualConnectDeviceHotspotActivity.Companion.launch(this, getIntent());
                break;
            default:
                runOnUiThread(() -> showToast(R.string.failed_to_config_wifi));
                break;
        }
    }

    private void startConfig() {
        if (mPresenter != null) {
            mPresenter.setActivity(this);
            mPresenter.setCallback(this);
            mPresenter.startConfigWifi(getApplication(), getIntent());
        }
    }

    private void stopConfig() {
        if (mPresenter != null) {
            mPresenter.setCallback(null);
            mPresenter.stopConfigWifi();
        }
    }
}
