package com.swiftcleaner.chovey.view;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.messaging.FirebaseMessaging;
import com.gyf.immersionbar.ImmersionBar;

import com.swiftcleaner.chovey.R;
import com.swiftcleaner.chovey.databinding.ActivityMainBinding;
import com.swiftcleaner.chovey.model.tool.MemoryUtils;
import com.swiftcleaner.chovey.view.activity.AppProcessActivity;
import com.swiftcleaner.chovey.view.activity.BatteryInfoActivity;
import com.swiftcleaner.chovey.view.activity.CleanJunkActivity;
import com.swiftcleaner.chovey.view.activity.InfoActivity;
import com.swiftcleaner.chovey.view.activity.LargeFileActivity;
import com.swiftcleaner.chovey.view.activity.ScreenShotActivity;
import com.swiftcleaner.chovey.view.activity.SettingActivity;
import com.swiftcleaner.chovey.view.activity.SimilarPhotosActivity;
import com.swiftcleaner.chovey.view.activity.WhatsAppActivity;
import com.swiftcleaner.chovey.view.dialog.AppExitDialog;
import com.swiftcleaner.chovey.view.dialog.CustomBottomSheetDialog;

public class MainActivity extends AppCompatActivity {
    ActivityMainBinding binding;
    private static final int REQUEST_ALL_FILES_ACCESS_PERMISSION = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        View view = binding.getRoot();
        setContentView(view);
        initBar();
        initShow();
        FirebaseMessaging.getInstance().getToken()
                .addOnCompleteListener(new OnCompleteListener<String>() {
                    @Override
                    public void onComplete(@NonNull Task<String> task) {
                        if (!task.isSuccessful()) {
                            Log.w("TAG", "Fetching FCM registration token failed", task.getException());
                            return;
                        }

                        // Get new FCM registration token
                        String token = task.getResult();

                        // Log and toast
                        Log.d("TAG", token);
                        Toast.makeText(MainActivity.this, token, Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private void initShow() {
        //判断是否有权限
        checkAndRequestPermissions();
        binding.lottieAnimattionView.setAnimation(R.raw.cleaner_junk_found_animation);
        binding.lottieAnimattionView.playAnimation();
        // 获取总内存
        String totalMemory = MemoryUtils.getUsedDiskMemory(this);

        // 获取当前使用内存
        String usedMemory = MemoryUtils.getTotalDiskMemory(this);
        //内存赋值
        binding.phoneMemory.setText(totalMemory + "/" + usedMemory);

        binding.cleanUp.setOnClickListener(v -> {
            intTempJump();
        });

        binding.ivSetting.setOnClickListener(v -> {
            Intent intent = new Intent(this, SettingActivity.class);
            startActivity(intent);
        });
        binding.cl3CleanJunk.setOnClickListener(v -> {
            Intent intent = new Intent(this, CleanJunkActivity.class);
            startActivity(intent);
        });
        binding.cl3AppManager.setOnClickListener(v -> {
            startActivity(new Intent(this, BatteryInfoActivity.class));
        });
        binding.cl3BatteryInfo.setOnClickListener(v -> {
            startActivity(new Intent(this, InfoActivity.class));
        });
        binding.appProcess.setOnClickListener(v -> {
            startActivity(new Intent(this, AppProcessActivity.class));
        });
        binding.largeFileCleaner.setOnClickListener(v -> {
            startActivity(new Intent(this, LargeFileActivity.class));
        });
        binding.screenshotCleaner.setOnClickListener(v -> {
            startActivity(new Intent(this, ScreenShotActivity.class));
        });
        binding.whatsApp.setOnClickListener(v -> {
            startActivity(new Intent(this, WhatsAppActivity.class));
        });
        binding.similarPhotos.setOnClickListener(v -> {
            startActivity(new Intent(this, SimilarPhotosActivity.class));
        });
    }

    private void checkAndRequestPermissions() {
        if (checkFilesAccessPermission(this)) {
            // 有权限，直接跳转页面
            
        } else {
            // 没有权限，请求权限
            CustomBottomSheetDialog customBottomSheetDialog = new CustomBottomSheetDialog();
            customBottomSheetDialog.setOnOpenSettingClickListener(isSwitchChecked -> {
                if (isSwitchChecked) {
                    requestFilesAccessPermission();
                    customBottomSheetDialog.dismiss();
                } else {
                    customBottomSheetDialog.dismiss();
                }
            });
            customBottomSheetDialog.show(getSupportFragmentManager(), "CustomBottomSheetDialog");
        }
    }

    private boolean checkFilesAccessPermission(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            return Environment.isExternalStorageManager();
        } else {
            int readPermission = ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE);
            int writePermission = ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE);
            return readPermission == PackageManager.PERMISSION_GRANTED && writePermission == PackageManager.PERMISSION_GRANTED;
        }
    }

    private void requestFilesAccessPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
            intent.addCategory("android.intent.category.DEFAULT");
            intent.setData(Uri.parse("package:" + getPackageName()));
            startActivityForResult(intent, REQUEST_ALL_FILES_ACCESS_PERMISSION);
        } else {
            // 在Android 10及以下版本，请求READ_EXTERNAL_STORAGE和WRITE_EXTERNAL_STORAGE权限
            // 通常使用请求权限的对话框
            // 例如： ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_PERMISSION_CODE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_ALL_FILES_ACCESS_PERMISSION) {
            if (checkFilesAccessPermission(this)) {
                // 权限已授予，跳转页面

            } else {
                // 权限未授予，显示提示信息或进行其他处理
                Toast.makeText(this, "权限未授权", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void intTempJump() {
        Intent intent = new Intent(this, CleanJunkActivity.class);
        startActivity(intent);
    }


    private void initBar() {
        ImmersionBar.with(this)
                .transparentStatusBar()  // 透明状态栏
                .statusBarDarkFont(true)  // 状态栏字体颜色为深色
                .navigationBarDarkIcon(false)  // 导航栏图标颜色为浅色
                .init();
    }

    @Override
    public void onBackPressed() {
        AppExitDialog appExitDialog = new AppExitDialog(this);
        appExitDialog.setOnDialogClickListener(new AppExitDialog.OnDialogClickListener() {
            @Override
            public void onCancel() {
                appExitDialog.dismiss();
            }

            @Override
            public void onSubmit() {
                finish();
            }
        });
        appExitDialog.show();
    }
    @Override
    protected void onResume() {
        super.onResume();
        if (binding.lottieAnimattionView != null) {
            binding.lottieAnimattionView.resumeAnimation(); // 恢复动画
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (binding.lottieAnimattionView != null) {
            binding.lottieAnimattionView.pauseAnimation();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (binding.lottieAnimattionView != null) {
            binding.lottieAnimattionView.cancelAnimation(); // 停止动画
            binding.lottieAnimattionView.clearAnimation(); // 清除动画
            binding.lottieAnimattionView.setImageDrawable(null); // 清除图像
            binding.lottieAnimattionView.destroyDrawingCache(); // 销毁缓存
        }
    }
}