package com.swiftcleaner.chovey.view;

import static com.swiftcleaner.chovey.GlobalConfig.ID_NOT_CLEANED;
import static com.swiftcleaner.chovey.GlobalConfig.ID_WHEATHER;
import static com.swiftcleaner.chovey.GlobalConfig.ID_XINGZUO;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.gyf.immersionbar.ImmersionBar;

import com.swiftcleaner.chovey.CleanApplication;
import com.swiftcleaner.chovey.R;
import com.swiftcleaner.chovey.business.admob.AdmobManager;
import com.swiftcleaner.chovey.business.push.NotificationUtils;
import com.swiftcleaner.chovey.databinding.ActivityMainBinding;
import com.swiftcleaner.chovey.model.tool.MemoryUtils;
import com.swiftcleaner.chovey.model.util.PermissionUtils;
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.FullscreenDialog;
import com.swiftcleaner.chovey.view.dialog.NoticeDialog;
import com.swiftcleaner.chovey.view.function.constellation.XzLoadingActivity;
import com.swiftcleaner.chovey.view.function.weather.WeatherInterface;

import java.util.concurrent.atomic.AtomicBoolean;

import io.reactivex.rxjava3.annotations.Nullable;

public class MainActivity extends AppCompatActivity {
    ActivityMainBinding binding;
    private ActivityResultLauncher<String[]> multiplePermissionsLauncher;
    private ActivityResultLauncher<Intent> notificationSettingsLauncher;
    private FullscreenDialog fullscreenDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        View view = binding.getRoot();
        setContentView(view);
        initBar();

        if (!isCleaned()) {
            fullscreenDialog = new FullscreenDialog(this);
            fullscreenDialog.setOnDialogDismissListener(new FullscreenDialog.OnDialogDismissListener() {
                @Override
                public void onSuccButton() {
                    startActivity(new Intent(MainActivity.this, CleanJunkActivity.class));
                }
            });
            fullscreenDialog.show();
        }

        initPermission();
        initShow();
//        binding.jiantou.setOnClickListener(v->{
//            NotificationUtils.INSTANCE.sendNotification(
//                    CleanApplication.context,
//                    ID_XINGZUO,
//                    "xingzuo"
//            );
//            NotificationUtils.INSTANCE.sendNotification(
//                    CleanApplication.context,
//                    ID_WHEATHER,
//                    "wheather"
//            );
//            Log.d("NotificationUtils","111");
//        });
    }

    private boolean isCleaned() {
        SharedPreferences prefs = getSharedPreferences("AppPrefs", MODE_PRIVATE);
        return prefs.getBoolean("cleaned", false);
    }

    private void initShow() {
        binding.lottieAnimattionView.setAnimation(R.raw.cleaner_junk_found_animation);
        binding.lottieAnimattionView.playAnimation();
        //判断是否有权限
//        NotificationUtils.INSTANCE.sendNotification(CleanApplication.context, GlobalConfig.ID_CLEAN_JUNK, "app_receiver");

        // 获取总内存
        String totalMemory = MemoryUtils.getUsedDiskMemory(this);

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

        binding.cleanUp.setOnClickListener(v -> {
            intTempJump();
        });
        binding.ivSetting.setOnClickListener(v -> {
//            AdmobManager.INSTANCE.showInterstitialAd(this, () -> {
//                        initSetting();
//                        return null;
//                    },
//                    () -> {
//                        return null;
//                    },
//                    () -> {
//                        initSetting();
//                        return null;
//                    });
            initSetting();

        });
        binding.cl3CleanJunk.setOnClickListener(v -> {
            intTempJump();
        });
        binding.cl3AppManager.setOnClickListener(v -> {
            startActivity(new Intent(MainActivity.this, BatteryInfoActivity.class));
        });
        binding.cl3BatteryInfo.setOnClickListener(v -> {
            startActivity(new Intent(MainActivity.this, InfoActivity.class));
        });
        binding.appProcess.setOnClickListener(v -> {
            startActivity(new Intent(MainActivity.this, AppProcessActivity.class));
        });
        binding.largeFileCleaner.setOnClickListener(v -> {
            startActivity(new Intent(MainActivity.this, LargeFileActivity.class));
        });
        binding.screenshotCleaner.setOnClickListener(v -> {
            startActivity(new Intent(MainActivity.this, ScreenShotActivity.class));
        });
        binding.whatsApp.setOnClickListener(v -> {
            startActivity(new Intent(MainActivity.this, WhatsAppActivity.class));
        });
        binding.similarPhotos.setOnClickListener(v -> {
            startActivity(new Intent(MainActivity.this, SimilarPhotosActivity.class));
        });
        binding.xingzuo.setOnClickListener(v -> {
            startActivity(new Intent(MainActivity.this, XzLoadingActivity.class));
        });
        binding.clTianqi.setOnClickListener(v -> {
            startActivity(new Intent(MainActivity.this, WeatherInterface.class));
        });
    }

    private void initPermission() {
        multiplePermissionsLauncher = registerForActivityResult(
                new ActivityResultContracts.RequestMultiplePermissions(),
                result -> {
                    if (result.get(Manifest.permission.POST_NOTIFICATIONS) != null && result.get(Manifest.permission.POST_NOTIFICATIONS)) {

                    }
                }
        );


        notificationSettingsLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    // 处理结果
                }
        );
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
                NoticeDialog noticeDialog = new NoticeDialog(this);
                noticeDialog.setOnDialogClickListener(new NoticeDialog.OnDialogClickListener() {
                    @Override
                    public void onCancel() {
                        noticeDialog.cancel();
                    }

                    @Override
                    public void onSubmit() {
                        // 请求通知权限
                        PermissionUtils.requestNotificationPermission(MainActivity.this, notificationSettingsLauncher, multiplePermissionsLauncher);
                        noticeDialog.cancel();
                    }
                });
                noticeDialog.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() {
                finishAffinity();
                System.exit(0); // 完全退出应用
            }
        });
        appExitDialog.show();
    }

    private AtomicBoolean bannerShowed = new AtomicBoolean(false);

    @Override
    protected void onResume() {
        super.onResume();
        if (isCleaned() && fullscreenDialog != null) {
            Log.d("isCleaned", isCleaned() + "222");
            fullscreenDialog.dismiss();
            fullscreenDialog = null; // 释放引用
        }
        if (bannerShowed.get()) return;
        bannerShowed.set(true);
        AdmobManager.INSTANCE.showBannerAd(this, binding.flBanner, "bottom", null, null);
        if (binding.lottieAnimattionView != null) {
            binding.lottieAnimattionView.resumeAnimation(); // 恢复动画
        }

        AdmobManager.INSTANCE.showNativeAd(this, (nativeAd) -> {
            binding.flAd.removeAllViews();
            binding.flAd.setNativeAd(nativeAd, R.layout.layout_ad_native);
            return null;
        }, null, null);

    }

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

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