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 static com.swiftcleaner.chovey.GlobalConfig.URL_PRIVACY;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Paint;
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.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.Toast;

import com.clean.file.b.business.newAdmob.AdmobHelps;
import com.gyf.immersionbar.ImmersionBar;

import com.swiftcleaner.chovey.CleanApplication;
import com.swiftcleaner.chovey.GlobalConfig;
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.databinding.DialogMalwareTipsBinding;
import com.swiftcleaner.chovey.model.tool.MemoryUtils;
import com.swiftcleaner.chovey.model.util.NetWork;
import com.swiftcleaner.chovey.model.util.PermissionUtils;
import com.swiftcleaner.chovey.view.activity.AnimatorActivity;
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.MalwareCleanActivity;
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.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.ListBean;
import com.swiftcleaner.chovey.view.function.weather.WeatherBean;
import com.swiftcleaner.chovey.view.function.weather.WeatherInterface;
import com.swiftcleaner.chovey.view.function.weather.WeatherUtils;

import org.checkerframework.checker.units.qual.A;

import java.util.Random;
import java.util.concurrent.atomic.AtomicBoolean;

public class MainActivity extends AppCompatActivity {
    ActivityMainBinding binding;
    private ActivityResultLauncher<String[]> multiplePermissionsLauncher;
    private ActivityResultLauncher<Intent> notificationSettingsLauncher;
    private FullscreenDialog fullscreenDialog;
    private static final int REQUEST_CODE_STORAGE_PERMISSION = 101;
    private static final int REQUEST_ALL_FILES_ACCESS_PERMISSION = 100;
    private static final int REQUEST_PERMISSION_CODE = 102;
    private CustomBottomSheetDialog customBottomSheetDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        View view = binding.getRoot();
        setContentView(view);
        initBar();
        initDialog();
        initPermission();
        initShow();
        binding.cl3VirusScan.setOnClickListener(v->{
            NetWork netWork = new NetWork();
            boolean networkAvailable = netWork.isNetworkAvailable(this);
            if (networkAvailable){
                showTipsDialog(this, () -> {
                    qx();
                });
            }else {
                Toast.makeText(this, this.getString(R.string.no_network_try_again), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void initDialog() {
        if (!isCleaned()) {
            fullscreenDialog = new FullscreenDialog(this);
            fullscreenDialog.setOnDialogDismissListener(new FullscreenDialog.OnDialogDismissListener() {
                @Override
                public void onSuccButton() {
                    if (!checkFilesAccessPermission(MainActivity.this)) {
                        // 没有权限，请求权限
                        customBottomSheetDialog = new CustomBottomSheetDialog();
                        customBottomSheetDialog.setOnOpenSettingClickListener(new CustomBottomSheetDialog.OnOpenSettingClickListener() {
                            @Override
                            public void onOpenSettingClick() {
                                requestFilesAccessPermission();
                            }

                            @Override
                            public void onCloseSettingClick() {
                                customBottomSheetDialog.dismiss();
                                fullscreenDialog.dismiss();
                            }
                        });
                        customBottomSheetDialog.show(getSupportFragmentManager(),"CustomBottomSheetDialog");
                    }else {
                        initStart();
                    }
                }
            });
            fullscreenDialog.show();
        }
    }

    private void qx() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||
                ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            // 如果没有权限，请求权限
            ActivityCompat.requestPermissions(this, new String[]{
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
            }, REQUEST_CODE_STORAGE_PERMISSION);
        } else {
            // 如果已经有权限，执行相关操作
            performPermissionGrantedAction();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == REQUEST_CODE_STORAGE_PERMISSION) {
            if (grantResults.length > 0 &&
                    grantResults[0] == PackageManager.PERMISSION_GRANTED &&
                    grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                // 用户授予了权限
                performPermissionGrantedAction();
            } else {
                // 用户拒绝了权限
                performPermissionGrantedAction();
            }
        }
        if (requestCode == REQUEST_ALL_FILES_ACCESS_PERMISSION || requestCode == REQUEST_PERMISSION_CODE) {
            if (!checkFilesAccessPermission(this)) {
                // 权限未授予，直接关闭页面
                Toast.makeText(this, "Unauthorized permission, the page is about to close", Toast.LENGTH_SHORT).show();
                fullscreenDialog.dismiss();
                customBottomSheetDialog.dismiss();
            }
        }

    }

    private void performPermissionGrantedAction() {
        startActivity(new Intent(this,MalwareCleanActivity.class));
    }

    public void showTipsDialog(Context context, final Runnable confirm) {
        if (!isCleanedBingDu()) {
            DialogMalwareTipsBinding binding = DialogMalwareTipsBinding.inflate(LayoutInflater.from(context));
            Dialog dialog = new Dialog(context,R.style.TransparentDialogTheme);
            //dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setCanceledOnTouchOutside(true);
            dialog.setCancelable(true);
            dialog.setContentView(binding.getRoot());
            dialog.show();

            binding.tvCancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                }
            });
            SharedPreferences prefs = getSharedPreferences("CleanBingDu", MODE_PRIVATE);
            binding.tvSure.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    SharedPreferences.Editor edit = prefs.edit();
                    edit.putBoolean("cleanbd",true);
                    edit.commit();
                    v.setEnabled(false);
                    dialog.dismiss();
                    confirm.run();
                }
            });

            binding.tvContent8.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    context.startActivity(
                            new Intent(Intent.ACTION_VIEW, Uri.parse(context.getString(R.string.trustlook_privacy_policy)))
                    );
                }
            });

            binding.tvContent8.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);

            binding.tvContent10.setText(URL_PRIVACY);
            binding.tvContent10.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    context.startActivity(
                            new Intent(Intent.ACTION_VIEW, Uri.parse(URL_PRIVACY))
                    );
                }
            });

            binding.tvContent10.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
        } else {
            confirm.run();
        }
    }
    private boolean isCleaned() {
        SharedPreferences prefs = getSharedPreferences("AppPrefs", MODE_PRIVATE);
        return prefs.getBoolean("cleaned", false);
    }
    private boolean isCleanedBingDu() {
        SharedPreferences prefs = getSharedPreferences("CleanBingDu", MODE_PRIVATE);
        return prefs.getBoolean("cleanbd", false);
    }
    private void initShow() {

        initWheather();
        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 -> {
            initStart();
        });
        binding.ivSetting.setOnClickListener(v -> {
            initSetting();
        });
        binding.cl3CleanJunk.setOnClickListener(v -> {
            initStart();
        });
        binding.cl3AppManager.setOnClickListener(v -> {
            Intent intent = new Intent(this, AnimatorActivity.class);
            intent.putExtra("animator",7);
            startActivity(intent);
        });
        binding.cl3BatteryInfo.setOnClickListener(v -> {
            Intent intent = new Intent(this, AnimatorActivity.class);
            intent.putExtra("animator",2);
            startActivity(intent);
        });
        binding.appProcess.setOnClickListener(v -> {
            Intent intent = new Intent(this, AnimatorActivity.class);
            intent.putExtra("animator",6);
            startActivity(intent);
        });
        binding.largeFileCleaner.setOnClickListener(v -> {
            Intent intent = new Intent(this, AnimatorActivity.class);
            intent.putExtra("animator",3);
            startActivity(intent);
        });
        binding.screenshotCleaner.setOnClickListener(v -> {
            Intent intent = new Intent(this, AnimatorActivity.class);
            intent.putExtra("animator",4);
            startActivity(intent);
        });
        binding.whatsApp.setOnClickListener(v -> {
            Intent intent = new Intent(this, AnimatorActivity.class);
            intent.putExtra("animator",8);
            startActivity(intent);
        });
        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 initWheather() {
        WeatherBean weatherEntity = WeatherUtils.INSTANCE.getWeatherEntity();
        if (weatherEntity!= null &&!weatherEntity.getList().isEmpty()) {
            ListBean bean = weatherEntity.getList().get(0);
            int value = 22;
            int min = Integer.parseInt(bean.getTempMin());
            int max = Integer.parseInt(bean.getTempMax());

            if (min == max) {
                value = max;
            } else if (min < max) {
                Random random = new Random();
                value = random.nextInt(max - min) + min;
            }

            int icon;
            String weatherType = WeatherUtils.INSTANCE.getWeatherType(Integer.parseInt(bean.getIconDay()));
            switch (weatherType) {
                case "Sunny day":
                    icon = R.mipmap.x_qing;
                    break;
                case "Cloudy day":
                    icon = R.mipmap.x_yin;
                    break;
                case "Rainy day":
                    icon = R.mipmap.x_dayu;
                    break;
                case "Snowy day":
                    icon = R.mipmap.x_xiaxue;
                    break;
                case "Greasy day":
                    icon = R.mipmap.x_wumaishachengbao;
                    break;
                case "Unknown":
                    icon = R.mipmap.x_qing;
                    break;
                default:
                    icon = R.mipmap.x_qing;
                    break;
            }

            binding.clTianqiSize.setText(String.valueOf(value));
            binding.clTianqiImg.setImageResource(icon);
        }else {
            binding.clTianqiSize.setText("");
            binding.clTianqiImg.setImageResource(R.mipmap.duoyun);
        }
    }
    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 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) {
            try {
                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);
            } catch (ActivityNotFoundException e) {
                Toast.makeText(this, "Unable to request permission, please grant manually", Toast.LENGTH_SHORT).show();
            }
        } else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_PERMISSION_CODE);
        }
    }


    private void initStart() {
        Intent intent = new Intent(this, AnimatorActivity.class);
        intent.putExtra("animator",1);
        startActivity(intent);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_ALL_FILES_ACCESS_PERMISSION) {
            // 检查权限是否已经授予
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                if (Environment.isExternalStorageManager()) {
                    // 权限已授予，刷新页面或执行相关操作
                    Intent intent = new Intent(this, CleanJunkActivity.class);
                    startActivity(intent);
                    fullscreenDialog.dismiss();
                    customBottomSheetDialog.dismiss();
                } else {
                    fullscreenDialog.dismiss();
                    customBottomSheetDialog.dismiss();
                    // 权限未授予，提示用户
                    Toast.makeText(this, "Permission not granted, please grant manually", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    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; // 释放引用
        }
        Log.e("isShowAdNative",AdmobManager.INSTANCE.isShowAdNative()+"");
        AdmobHelps.INSTANCE.showNativeAd(this,binding.flAd,R.layout.layout_ad_native_small,AdmobHelps.INSTANCE.isShowAdNativeBottom(),false);
        if (binding.lottieAnimattionView != null) {
            binding.lottieAnimattionView.resumeAnimation(); // 恢复动画
        }

        if (bannerShowed.get()) return;
        bannerShowed.set(true);
        if (AdmobManager.INSTANCE.isShowAdBanner()){
            AdmobHelps.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(); // 销毁缓存
        }
        if (fullscreenDialog!= null) {
            fullscreenDialog.dismiss();
            fullscreenDialog = null; // 释放引用
        }
        if (customBottomSheetDialog!= null) {
            customBottomSheetDialog.dismiss();
            customBottomSheetDialog=null;
        }
    }
}