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;
import com.zxdemo.admob.AdmobHelper;

import java.util.concurrent.atomic.AtomicBoolean;

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();
    }

    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 -> {
            AdmobHelper.INSTANCE.showInterstitialAd(this, () -> {
                        intTempJump();
                        return null;
                    },
                    () -> {
                        return null;
                    },
                    () -> {
                        intTempJump();
                        return null;
                    });
        });
        binding.ivSetting.setOnClickListener(v -> {
//            AdmobHelper.INSTANCE.showInterstitialAd(this, () -> {
//                        initSetting();
//                        return null;
//                    },
//                    () -> {
//                        return null;
//                    },
//                    () -> {
//                        initSetting();
//                        return null;
//                    });
            initSetting();

        });
        binding.cl3CleanJunk.setOnClickListener(v -> {
            AdmobHelper.INSTANCE.showInterstitialAd(this, () -> {
                        intTempJump();
                        return null;
                    },
                    () -> {
                        return null;
                    },
                    () -> {
                        intTempJump();
                        return null;
                    });

        });
        binding.cl3AppManager.setOnClickListener(v -> {
            AdmobHelper.INSTANCE.showInterstitialAd(this, () -> {
                        startActivity(new Intent(this, BatteryInfoActivity.class));
                        return null;
                    },
                    () -> {
                        return null;
                    },
                    () -> {
                        startActivity(new Intent(this, BatteryInfoActivity.class));
                        return null;
                    });

        });
        binding.cl3BatteryInfo.setOnClickListener(v -> {
            AdmobHelper.INSTANCE.showInterstitialAd(this, () -> {
                        startActivity(new Intent(this, InfoActivity.class));
                        return null;
                    },
                    () -> {
                        return null;
                    },
                    () -> {
                        startActivity(new Intent(this, InfoActivity.class));
                        return null;
                    });

        });
        binding.appProcess.setOnClickListener(v -> {
            AdmobHelper.INSTANCE.showInterstitialAd(this, () -> {
                        startActivity(new Intent(this, AppProcessActivity.class));
                        return null;
                    },
                    () -> {
                        return null;
                    },
                    () -> {
                        startActivity(new Intent(this, AppProcessActivity.class));
                        return null;
                    });

        });
        binding.largeFileCleaner.setOnClickListener(v -> {
            AdmobHelper.INSTANCE.showInterstitialAd(this, () -> {
                        startActivity(new Intent(this, LargeFileActivity.class));
                        return null;
                    },
                    () -> {
                        return null;
                    },
                    () -> {
                        startActivity(new Intent(this, LargeFileActivity.class));
                        return null;
                    });

        });
        binding.screenshotCleaner.setOnClickListener(v -> {
            AdmobHelper.INSTANCE.showInterstitialAd(this, () -> {
                        startActivity(new Intent(this, ScreenShotActivity.class));
                        return null;
                    },
                    () -> {
                        return null;
                    },
                    () -> {
                        startActivity(new Intent(this, ScreenShotActivity.class));
                        return null;
                    });

        });
        binding.whatsApp.setOnClickListener(v -> {
            AdmobHelper.INSTANCE.showInterstitialAd(this, () -> {
                        startActivity(new Intent(this, WhatsAppActivity.class));
                        return null;
                    },
                    () -> {
                        return null;
                    },
                    () -> {
                        startActivity(new Intent(this, WhatsAppActivity.class));
                        return null;
                    });
        });
        binding.similarPhotos.setOnClickListener(v -> {
            AdmobHelper.INSTANCE.showInterstitialAd(this, () -> {
                        startActivity(new Intent(this, SimilarPhotosActivity.class));
                        return null;
                    },
                    () -> {
                        return null;
                    },
                    () -> {
                        startActivity(new Intent(this, SimilarPhotosActivity.class));
                        return null;
                    });

        });
    }

    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 initSetting() {
        Intent intent = new Intent(this, SettingActivity.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();
    }

    private AtomicBoolean bannerShowed = new AtomicBoolean(false);

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

        if (checkFilesAccessPermission(this)) {
            if (bannerShowed.get()) return;
            bannerShowed.set(true);
            AdmobHelper.INSTANCE.showBannerAd(this, binding.flBanner, "bottom", null, null);
        }
    }

    @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(); // 销毁缓存
        }
    }
}