package com.rdiot.yx485;

import static com.rdiot.yx485.UpdateMgr.GET_UNKNOWN_APP_SOURCES;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.webkit.CookieManager;

import androidx.lifecycle.ViewModelProvider;

import com.rdiot.yx485.databinding.ActivityCheckUpdateBinding;
import com.rdiot.yx485.main.MainViewModel;
import com.zcolin.frame.util.FileUtil;

import java.io.File;

public class CheckUpdateActivity extends BaseActivity {
    private ActivityCheckUpdateBinding mBinding;
    private MainViewModel mViewModel;
    private String updataurl;
    private String updateData;
    private boolean isForceUpdate;

    // 辅助方法：递归删除目录下的所有文件
    private static boolean deleteDir(File dir) {
        if (dir != null && dir.isDirectory()) {
            String[] children = dir.list();
            for (String aChildren : children) {
                boolean success = deleteDir(new File(dir, aChildren));
                if (!success) {
                    return false;
                }
            }
        }
        return dir.delete();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = ActivityCheckUpdateBinding.inflate(getLayoutInflater());
        setContentView(mBinding.getRoot());

        mViewModel = new ViewModelProvider(this).get(MainViewModel.class);
        initView();
        observeViewModel();
    }

    private void observeViewModel() {
        mViewModel.getNeedUpdate().observe(this, needUpdate -> {
            if (!needUpdate) {
                showMessage("当前已是最新版本");
            }
        });

        mViewModel.getUpdateInfo().observe(this, updateInfo -> {
            if (updateInfo != null) {
                updataurl = updateInfo.download_url;
                updateData = updateInfo.content;
                isForceUpdate = updateInfo.force_update;

                String content = updateInfo.content;
                if (content == null || content.isEmpty()) {
                    content = "发现新版本 " + updateInfo.version + "\n是否更新？";
                }

                showUpdateDialog(content, isForceUpdate);
            }
        });

        mViewModel.getErrorMessage().observe(this, this::showMessage);
    }

    private void initView() {
        mBinding.layoutTitle.tvTitle.setText("系统设置");
        mBinding.layoutTitle.btnTitleLeft.setOnClickListener(v -> finish());
        mBinding.update.setOnClickListener(view -> mViewModel.checkUpdate());
        mBinding.btnClearCache.setOnClickListener(v -> clearCache());
    }

    private void clearCache() {
        // 清除内存中的缓存（仅清除页面加载数据）
        mBinding.webView.clearCache(true);

        // 清除所有持久化的存储，包括文件系统和数据库
        getApplicationContext().deleteDatabase("webview.db");
        getApplicationContext().deleteDatabase("webviewCache.db");

        // 对于API 21及以上，还需要考虑清除Service Worker缓存
        CookieManager.getInstance().removeAllCookies(null);
        CookieManager.getInstance().flush();

        // 清除应用内部存储空间的缓存目录
        clearAppCache();
        showMessage("清除缓存成功");
    }

    public void clearAppCache() {
        try {
            File dir = getCacheDir(); // 获取应用内部缓存目录
            if (dir != null && dir.isDirectory()) {
                deleteDir(dir); // 使用上面定义的辅助方法删除目录及其内容
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 更新弹窗
     */
    private void showUpdateDialog(String content, boolean forceUpdate) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("系统更新")
                .setMessage(content)
                .setPositiveButton("更新", (dialog, which) -> {
                    String url = getFilesDir() + "/wuheng.apk";
                    File file = new File(url);
                    FileUtil.delete(file);
                    UpdateMgr.checkPermission(this, updataurl);
                });

        if (!forceUpdate) {
            builder.setNegativeButton("暂不更新", null);
        }

        AlertDialog alertDialog = builder.create();
        alertDialog.setCancelable(!forceUpdate);
        alertDialog.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK && requestCode == GET_UNKNOWN_APP_SOURCES) {
            showMessage("安装应用");
            showUpdateDialog(updateData, isForceUpdate);
        }
    }
}