package com.ttstd.controlled.activity.activation;

import android.content.Intent;
import android.os.Build;
import android.view.View;
import android.widget.Toast;

import com.ttstd.controlled.R;
import com.ttstd.controlled.activity.main.MainActivity;
import com.ttstd.controlled.activity.settings.SettingsActivity;
import com.ttstd.controlled.base.mvvm.BaseMvvmActivity;
import com.ttstd.controlled.databinding.ActivityActivationBinding;
import com.ttstd.controlled.utils.DeviceUtils;

/**
 * 激活页。
 *
 * 设备未激活时展示提示信息，并提供「重新激活」按钮，
 * 点击后重新执行 provision + token 流程，成功后跳转主页。
 */
public class ActivationActivity extends BaseMvvmActivity<ActivationViewModel, ActivityActivationBinding> {

    @Override
    protected int getLayoutId() {
        return R.layout.activity_activation;
    }

    @Override
    protected void initView() {
        binding.tvMessage.setText(R.string.activation_hint);
        binding.tvDeviceInfo.setText(
                getString(R.string.activation_device_info, Build.MODEL, DeviceUtils.getStableId(this)));

        binding.btnRetry.setOnClickListener(v -> viewModel.activate());
        binding.btnSettings.setOnClickListener(v ->
                startActivity(new Intent(this, SettingsActivity.class)));
    }

    @Override
    protected void initData() {
        viewModel.init(this);

        viewModel.getLoading().observe(this, loading -> {
            boolean isLoading = Boolean.TRUE.equals(loading);
            binding.progressBar.setVisibility(isLoading ? View.VISIBLE : View.GONE);
            binding.btnRetry.setEnabled(!isLoading);
            if (isLoading) {
                binding.tvMessage.setText(R.string.activation_activating);
            }
        });

        viewModel.getSuccess().observe(this, success -> {
            if (!Boolean.TRUE.equals(success)) return;
            Toast.makeText(this, R.string.activation_success, Toast.LENGTH_SHORT).show();
            startActivity(new Intent(this, MainActivity.class));
            finish();
        });

        viewModel.getError().observe(this, reason ->
                binding.tvMessage.setText(getString(R.string.activation_failed, reason)));

        // 进入页面即自动尝试激活一次，失败后用户可点击按钮重试。
        viewModel.activate();
    }
}
